PHP-访问数组内的数据

时间:2018-08-30 18:39:54

标签: php arrays

似乎无法解决如何访问其中具有其他数组的数组中的数据。

我的数组如下:

Array
(
    [0] => Array
        (
            [_id] => 28
            [serv_image] => 
            [serv_name] => My Service
            [slug] => my-service
            [is_featured] => 
            [_blocks] => Array
                (
                    [0] => Array
                        (
                            [anchor_heading] => Mats Heading
                            [_block_type] => anchorHeading
                            [_block_id] => pe8t69
                            [_block_index] => 0
                        )

                    [1] => Array
                        (
                            [anchor_heading] => Another anchored heading
                            [_block_type] => anchorHeading
                            [_block_id] => pea49u
                            [_block_index] => 1
                        )

                )

            [_page] => *
            [_pageID] => 1
            [_sortvalue] => 1003
        )

)

到目前为止,我已经尝试了此尝试,但没有成功:

foreach($services as $service) {
    print_r($service['_blocks']['anchor_heading']);
}

这将导致anchor_heading上的索引未定义。

更新

我将需要将它们分组为一个变量的数量未知。无论输入了多少次,我如何确保都能抓住它们?

3 个答案:

答案 0 :(得分:2)

每个_block都有一个数组..因此您需要一个索引访问..(或内部迭代)

foreach($services as $service) {
  print_r($service['_blocks'][0]['anchor_heading']);
  print_r($service['_blocks'][1]['anchor_heading']);
}

(或内部迭代)

  foreach($services as $service) {
      $blocks  = $service['_blocks'];
      foreach( $blocks as $block) {
          print_r($block['anchor_heading']);

      }
  }

答案 1 :(得分:2)

您可以使用foreach的2倍并回显anchor_heading的值:

foreach($services as $service) {
    foreach ($service["_blocks"] as $block) {
        echo $block["anchor_heading"];
    }
}

答案 2 :(得分:0)

您可以使用以下命令在for循环中访问数组中的数据:

print($service['_blocks'][0]['anchor_heading']);