kangular
kangular

Reputation: 263

PHP how to loop over nested JSON Object?

1. Extracted from my laravel controller:
        ..
        ..
        $data = json_decode($response, true);
        return $data;
        ..
        ..
        return view('homepage')->with('homeExclusives', $homeExclusives);

  1. Here is a sample of the returned data, just a short version, since the returned feed is very large, but this will give you an idea of the way it's structured.
     array(4) {
       ["success"]=> bool(true) 
       ["status"]=> int(200) 
       ["bundle"]=> array(2) {
           [0]=> array(631) {
               ["StreetDirPrefix"]=> string(2) "SW" 
               ["DistanceToStreetComments"]=> NULL
           }

           [1]=> array(631) { 
               ["StreetDirPrefix"]=> string(2) "NE" 
               ["DistanceToStreetComments"]=> NULL
              }
      }
  1. I need to extract "StreetDirPrefix" value from [0] and [1], but I always get an error. Can someone help?

Upvotes: 0

Views: 209

Answers (2)

SeeQue
SeeQue

Reputation: 51

Without knowing what error you are getting my solution would be something like this:

<?php
if (is_array($data) && is_array($data["bundle"]) ) {
    foreach ($data["bundle"] as $tmpKey => $tmpVal) {
        if (isset($tmpVal["StreetDirPrefix"])) {
            echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
        }
    }
}
?>

I always like to validate arrays, so if your $data variable or the $data["bundle"] subsection are not arrays then you will not get anything. Not even an error.

I have a working example here: https://www.seeque-secure.dk/demo.php?id=PHP+how+to+loop+over+nested+JSON+Object

EDIT:

(if i understand you correct) When you have validated your array all you have to do is repeat the inner validation like this:

<?php
if (is_array($data) && is_array($data["bundle"]) ) {
    foreach ($data["bundle"] as $tmpKey => $tmpVal) {
        if (isset($tmpVal["StreetDirPrefix"])) {
            echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
        }
        if (isset($tmpVal["UnparsedAddress"])) {
            echo $tmpVal["UnparsedAddress"]."\n";
        }
        if (isset($tmpVal["SalePrice"])) {
            echo $tmpVal["SalePrice"]."\n";
        }

        //...... ect.....

    }
}

?>

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163362

For the data in your example you might use array_column and specify StreetDirPrefix as the column key.

$res = array_column($array["bundle"], "StreetDirPrefix");
print_r($res);

Php demo

Upvotes: 1

Related Questions