Mike
Mike

Reputation: 980

Correctly outputting JSON with php?

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?

Upvotes: 0

Views: 66

Answers (1)

John Conde
John Conde

Reputation: 219794

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;

Upvotes: 3

Related Questions