简体   繁体   中英

PHP loop through nested JSON to find value

I am trying to loop through nested JSON data to find a name with a specific string and extract the string value associated with that. In this case the name string is "myKey" and the value string is "12345678".

After looking at several similar questions and documentation, I have tried different approaches such as doing it with objects or associative arrays, but still end up not being able to get to the information I want or receive errors.

Types of errors:

Notice: Array to string conversion

Warning: Invalid argument supplied for foreach()

Trying to get property of non-object

Here is a snippet of the decoded JSON using $myObj = json_decode($result);

object(stdClass)#4 (3) {
  ["info"]=>
  object(stdClass)#5 (10) {
    .
    .
    .
  }
  ["stuff"]=>
  array(1) {
    .
    .
    .
  }
  ["result"]=>
  array(3) {
    [0]=>
    object(stdClass)#7 (3) {
      ["name"]=>
      ["value"]=>
      ["description"]=>
    }
    [1]=>
    object(stdClass)#8 (2) {
      ["name"]=>
      string(4) "Units"
      ["value"]=>
      array(2) {
        [0]=>
        array(6) {
          [0]=>
          object(stdClass)#9 (3) {
            .
            .
            .
          }
          .
          .
          .
          [5]=>
          object(stdClass)#14 (2) {
            ["name"]=>
            string(10) "Components"
            ["value"]=>
            array(1) {
              [0]=>
              array(14) {
                [0]=>
                object(stdClass)#15 (3) {
                .
                .
                .
                }
                [1]=>
                object(stdClass)#16 (3) {
                  ["name"]=>
                  string(5) "myKey"
                  ["value"]=>
                  string(8) "12345678"
                  ["description"]=>
                }
                .
                .
                .

Here is a snippet of the PHP code I tried:

$myObj = json_decode($result);
// or I have tried
// $myObj = json_decode($result, true);


// here are different snippets of code I tried
foreach($myObj->result as $test) {
    echo '<pre>';
    print_r($test->name);
    echo "<br>";
    if ($test->name == "Units") {
        $resultName = $test->name;
        echo $resultName . "<br>";
    }
    echo '</pre>';
}

/*
foreach($myObj->result as $test) {
    echo $test . "<br>";
    foreach($test->name as $test1) {
        echo $test1 . "<br>";
        foreach($test1->value as $test2) {
            echo $test2 . "<br>";
        }
    }
}
*/

/*
foreach($myObj->result as $test) {
    if (($test->name) == "Units") {
        // grab the value that corresponds to the name
        $units = $test->name;
        if (($units->name) == "Components") {
            $components = $units->name;
            print_r($components);
        }
    }
}
*/

I can access what I need directly, by saying:

print_r($myObj->result[1]->value[0][5]->value[0][1]->name);
print_r($myObj->result[1]->value[0][5]->value[0][1]->value);

but the location of the value may vary, so I need to find the names of the objects by looping

Can anyone provide a better approach using objects (or possibly even associative arrays)?

UPDATED TO INCLUDE SNIPPET OF ORIGINAL JSON (before decode)

string(21420) "{
  "info": {
  .
  .
  .
  },
  "stuff": [{
    "name":
    "type":
    .
    .
    .
  }],
  "result": [
    {
      "name":
      "value":
      "description":
    },
    {
      "name": "Units",
      "value": [
        [
          {
            "name":
            "value":
            "description":
          },
          .
          .
          .
          {
            "name": "Components",
            "value": [
             [
               {
                 "name":
                 "value":
                 "description":
               },
               {
                 "name": "myKey",
                 "value": "12345678",
                 "description":
               },
               .
               .
               .
             ] (end inner Components value)
           ] (end outer Components value)
         ] (end inner Units value)
       ] (end outer Units value)
     } (end results Units)
   ] (end result)
 } (end opening)

It feels like you need some recursive function (a function that calls itself until it finds the the result) to find the value within the nested array.

Take a look at Recursive array_search

Of course you will have to change the function in that question, but I have similar issue once and it was very userful.

Below is the code for encoding and decoding. hope this helps you

 //Encoding 
    //Array Values
        $a1=array("name"=>"abc", "value"=>"def", "description"=>"ghi");
        $a2=array("name"=>"jkl", "value"=>"mno", "description"=>"pqr");
        $a3=array("name"=>"stu", "value"=>"wxy", "description"=>"zab");
    //Array of Value Arrays
        $info=array($a1, $a2, $a3);
        $result=array($a1, $a2, $a3);
        $stuff=array($a1, $a2, $a3);
    //The Main Enclosed Array
        $main=json_encode(array("info"=>$info, "result"=>$result, "stuff"=>$stuff));

    //Decoding  
    //Fetching the name from result's $a1 array
        $main_array=json_decode($main);
        echo $main_array->result[1]->name; //Displays jkl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM