How to loop through JSON array using PHP

后端 未结 4 2017
终归单人心
终归单人心 2020-12-31 06:25

My PHP code:

$obj = json_decode($data);
print $obj->{\'name\'};

While it works for non-arrays, I can\'t for the life of me figure out h

相关标签:
4条回答
  • 2020-12-31 06:58

    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.

    0 讨论(0)
  • 2020-12-31 07:01

    Here using objects example (to read reviews...raiting):

    $jsonObject = json_decode($data);
    foreach ($jsonObject->reviews as $data) {
        echo $data->rating;
    }
    
    0 讨论(0)
  • 2020-12-31 07:06

    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>";
    }
    
    0 讨论(0)
  • 2020-12-31 07:21

    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'];
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题