How to loop through JSON array using PHP

僤鯓⒐⒋嵵緔 提交于 2019-11-30 08:40:59

You are probably having trouble because reviews is an array and you are trying to access it as a JSON object.

$obj = json_decode($data, TRUE);
for($i=0; $i<count($obj['reviews']); $i++) {
    echo "Rating is " . $obj['reviews'][$i]["rating"] . " and the excerpt is " . $obj['reviews'][$i]["excerpt"] . "<BR>";
}

I'm not sure what exactly you want but I guess you want print it just for debugging right now. You can try with print_r($obj); and var_dump($obj); - they must print something, especially var_dump(). When you see the data, you can easily edit function a little bit, so you can do for instance print_r($obj->reviews) or print_r($obj['reviews']), depending if $obj is object or array.

You can use var_dump or print_r.

<?php 
$decodedJSON = json_decode($jsonData);

// Put everyting to the screen with var_dump;
var_dump($decodedJSON);

// With print_r ( useful for arrays );
print_r($decodedJSON);

// List just review ratings with foreach;
foreach($decodedJSON['reviews'] as $review){
    echo $review['rating'];
}
?>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!