2

PHP receives this via AJAX in JSON format (let's call it $json_string):

[{"pid":"284","qty":"1","sn":"12"},{"pid":"284","qty":"1","sn":"23"},{"pid":"276","qty":"1","sn":"34"},{"pid":"276","qty":"1","sn":"45"},{"pid":"276","qty":"1","sn":"56"},{"pid":"281","qty":"1","sn":"57"},{"pid":"281","qty":"1","sn":"67"},{"pid":"281","qty":"1","sn":"78"}]

I wish to loop through the arrays, like so:

$out = '<table>';
$arr = json_decode($json_string);
foreach ($arr AS $row){
    $out .= '<tr><td>'.$row['pid'].'</td><td>'.$row['qty'].'</td><td>'.$row['sn'].'</td></tr>';
}
$out .= '</table>';

I am getting an error: Fatal error: Cannot use object of type stdClass as array

2
  • Doesn't that mean that json_decode returns something that is NOT an array? Commented Jan 24, 2015 at 0:41
  • @ThomasKilian No, but $arr = json_decode($json_string, true) results in an associative array: $pid = $arr['pid']; -- whereas just $arr = json_decode($json_string) results in a simple array: $pid = $arr[0]; Depends on the data, not just the desired output. Above is assoc data. Commented Jan 24, 2015 at 1:05

1 Answer 1

8

You need to force it to use an associative array:

$arr = json_decode($json_string, true);

Or modify your code to use object notation for the objects:

foreach ($arr AS $row){
    $out .= '<tr><td>'.$row->pid.'</td><td>'.$row->qty.'</td><td>'.$row->sn.'</td></tr>';
}

Personally I prefer forcing it all to an associative array because its easier to work with, especially when you get into complex nested structures.

Sign up to request clarification or add additional context in comments.

1 Comment

It's stated pretty clear in json_decode documentation: php.net/manual/en/function.json-decode.php

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.