0

New to working with JSON. I have the following XML results. I'd like to offer the same results but in JSON format when requested. My data is coming from a mySQL array.

My problem comes in when I try to have multiple nodes of the same name. Take my XML result for instance:

<results>
    <result>
        <item_id>1</item_id>
    </result>
    <result>
        <item_id>50</item_id>
    </result>
    <result>
        <item_id>50433</item_id>
    </result>
    <result>
        <item_id>3</item_id>
    </result>
</results>

If I simply do something like the following in PHP, my data keeps overwriting eachother.

foreach($result as $key => $value) {
    $json["results"]["result"]["item_id"] = $value;
}

It gives me only one line of result which is the last item_id of 3.

What am I overlooking?

3
  • It looks like you keep setting the value of the same node in your loop.
    – woz
    Mar 13, 2013 at 1:30
  • Keeping the xmlish array levels is super unnatural. Slash result and item_id at the very least, if there's no further content.
    – mario
    Mar 13, 2013 at 1:31
  • thanks mario.. actually a ton of content in each <result>; just cut it out for an example
    – Mike
    Mar 13, 2013 at 1:32

1 Answer 1

3

You're overwriting your value in your loop because you're not putting it into an array.

$json["results"]["result"]["item_id"] = $value;

should be

$json["results"]["result"]["item_id"][] = $value;
2
  • Wouldn't you need to specify an index each time through the loop, or no? i.e. $json["results"]["result"]["item_id"][$i]
    – woz
    Mar 13, 2013 at 1:31
  • No. It will automatically increment as with any numeric key array.
    – John Conde
    Mar 13, 2013 at 1:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.