从 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"];
           }
     }
数组

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

 $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改变一些事情。请记住,json 中的{}映射到对象,而不是数组。

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

问题最终是在 foreach 循环中格式化。链接以下正确语法:

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