Thursday, 30 August 2018

Return objects from a JSON multidimensional array to PHP

I'm running into a few issues when trying to decode this JSON multidimensional array using PHP:

{"123456":{"info":[
{"maxlength":null,"value":"$Name","options_hash":null},
{"maxlength":null,"value":"$prefix","options_hash":{" Mr. ":"Mr."," Mrs. ":"Mrs."}},
                  ]
          }
}

I printed out the array using var_export so I could better understand the structure:
array (
  '123456' =>
  array (
    'info' =>
    array (
      0 =>
      array (
        'maxlength' => NULL,
        'value' => '$Name',
        'options_hash' => NULL,
      ),
      1 =>
      array (
        'maxlength' => NULL,
        'value' => '$prefix',
        'options_hash' =>
        array (
          ' Mr. ' => 'Mr.',
          ' Mrs. ' => 'Mrs.',
        ),
      ),

        ),
      ),
    ),
  ),
)

All I'm trying to do is print the value within the array within info, $Name and $Prefix.
I tried using a foreach loop, but I'm a bit confused on how it should be structured:
foreach ($json["123456"] as $info) 

     {
           $array = $info["info"];
           foreach($array as $values)
           {
                 echo $values["value"];
           }
     }


Array items are accessed by [], object items by ->
 $jsonStr= '{"123456":   {"info":[
      {"maxlength":null,"value":"$Name","options_hash":null},
      {"maxlength":null,"value":"$prefix","options_hash":{" Mr. ":"Mr."," Mrs. ":"Mrs."}}
   ]}}';

$json = json_decode($jsonStr);

foreach ($json as $level1) {  // this will give us everything nested to the same level as 123456
    foreach($level1 as $info) {  // this will give us everything nested to the same level as info
        foreach($info as $values)   {  // this will give us each of the items in the info array
            echo $values->value;  // this prints out the $Name and $prefix
        }
    }
}

// if you really want to start in a level
foreach($json->{'123456'} as $info) {  // this will give us everything nested to the same level as info
    foreach($info as $values)   {  // this will give us each of the items in the info array
        echo $values->value;  // this prints out the $Name and $Prefix
    }
}

0 comments:

Post a Comment