1

My goal is to loop through each Item within the JSON and add an additional key called "modal" to each "Item", and the value paired with that key that would contain html. I stripped down my code below.

I'm able to add 'modal' to each 'Item', however the value somehow gets set to null, instead of the html I would like it to be.

JSON file:

{"Item":{
"thumbnail":"http://...",
  "title": "Item title"
},
"Item":{
  "thumbnail":"http://...",
  "title": "Item title"
}}        

php:

$json_a=json_decode($json, true);

foreach ($json_a['Item'] as &$obj){
    $out = '<img src=\"' . $obj['thumbnail'] . '\">';
    $out .= '<span>' . $obj['title'] . '</span>';

    $obj['modal'] = $out; //value of $out doesn't get passed in, instead the value becomes null.
}

$json_a=json_encode($json_a);
print_r($json_a);

json output:

...{'modal': null}... 

Edited the JSON to be valid. It comes from Amazon's product API, I shortened it for this example and made it invalid.

2
  • 3
    How did you generate this json ??? Its not valid Commented Nov 18, 2012 at 21:14
  • The JSON actually comes from an API, i shortened it to give an example. I caused the json to become invalid, however JSON can have duplicate keys. Commented Nov 18, 2012 at 21:41

2 Answers 2

3

Your JSON is invalid. It is an object with duplicate keys ("Item"). You should use an array instead:

[
    {
        "thumbnail": "...",
        "title": "..."
    },
    {
        "thumbnail": "...",
        "title": "..."
    }
]

Then you can iterate over it and add 'modal' to all elements:

$json_a = json_decode($json, true);

foreach ($json_a as &$obj) {
    $out = '<img src=\"' . $obj['thumbnail'] . '\">';
    $out .= '<span>' . $obj['title'] . '</span>';

    $obj['modal'] = $out;
}

$json_a = json_encode($json_a);
print_r($json_a);
Sign up to request clarification or add additional context in comments.

Comments

1

Its simple your json is not valid

{
    "Item": {
        "thumbnail": "http://...",
        "title": "Item title",
                             ^---- This should not be here

    },

    "Item": {
       ^-------------- Duplicate name 
        "thumbnail": "http://...",
        "title": "Item title",
                             ^---- This should not be here

    }
}

The main issue is that you need to generate your object or array properly using json_encode if you are using PHP for the generation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.