PHP循环对象数组(JSON)

时间:2015-01-24 00:26:45

标签: php arrays json

PHP通过JSON格式的AJAX接收它(让我们称之为$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"}]

我希望遍历数组,如下所示:

$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>';

我收到错误:Fatal error: Cannot use object of type stdClass as array

1 个答案:

答案 0 :(得分:8)

您需要强制它使用关联数组:

$arr = json_decode($json_string, true);

或者修改代码以对对象使用对象表示法:

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

我个人更喜欢将它全部强制转换为关联数组,因为它更容易使用,特别是当你进入复杂的嵌套结构时。