从 PHP 中的 JSON 多维数组返回对象

Returning objects from a JSON multidimensional array in PHP

我 运行 在尝试使用 PHP:

解码这个 JSON 多维数组时遇到了一些问题
{"123456":{"info":[
{"maxlength":null,"value":"$Name","options_hash":null},
{"maxlength":null,"value":"$prefix","options_hash":{" Mr. ":"Mr."," Mrs. ":"Mrs."}},
                  ]
          }
}

我使用 var_export 打印出数组,以便更好地理解结构:

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.',
        ),
      ),

        ),
      ),
    ),
  ),
)

我想做的就是在信息、$Name 和 $Prefix 中打印数组中的值。

我尝试使用 foreach 循环,但我对它的结构有点困惑:

foreach ($json["123456"] as $info) 

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

您可能需要对 foreach 进行一些更改。请记住 json 中的 {} 映射到对象,而不是数组。

$json = json_decode($the_string);

foreach ($json->{'123456'} as $info) {
       echo $info->value;
 }

数组项由 [] 访问,对象项由 ->

访问
 $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
    }
}

问题最终出现在 foreach 循环中。链接以下正确语法:

foreach ($json->123456->info as $info) {
       echo $info->value;
 }

?>