使用Laravel阵列获取许多数据

时间:2018-08-30 07:28:04

标签: arrays json laravel

PHP代码:

$firstData =array (
  '000' => array (
  '000' => array (
   0 => '{"code":"11101000000","postal":"3310000"}',
    ),
  ),
  '000' => array (
  '000' =>array (
  0 => '{"code":"11101001000","postal":"3310058"}',
    ),
  ),
  '000' => array (
  '000' => array (
  0 => '{"code":"11101002000","postal":"3310068"}',
    ),
  ),
  '000' => array (
  '000' => array (
  0 => '{"code":"11101035001","postal":"3310078"}',
    ),
 ),  
);
$array_from_json = json_decode($firstData['000']['000'][0], true);
echo( $array_from_json['postal']);

输出结果:

  • 3310078

我想要这样。

  • 3310000 3310058 3310068 3310078

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

您的数组错误。您在顶级数组中有相同的键(所有键都是000),这就是您的问题。尝试像这样更改它们:

$firstData =array (
  '1' => array (
      '000' => array (
            0 => '{"code":"11101000000","postal":"3310000"}',
        ),
    ),
  '2' => array (
      '000' =>array (
            0 => '{"code":"11101001000","postal":"3310058"}',
        ),
    ),
  '3' => array (
      '000' => array (
            0 => '{"code":"11101002000","postal":"3310068"}',
        ),
    ),
  '4' => array (
      '000' => array (
            0 => '{"code":"11101035001","postal":"3310078"}',
        ),
    ),  
);

然后您可以访问您的邮政字段:

foreach($firstData as $data) {
    $array_from_json = json_decode($data['000'][0], true);
    echo($array_from_json['postal']);
}