PHP遍历数组内部的数组

时间:2018-10-08 13:44:47

标签: php arrays loops foreach

我试图遍历一个由两个分别具有2个属性的数组和另一个具有不同数量属性的数组组成的数组。 我试图使用foreach输出最后一个数组的所有属性。

 $gallery = array(
    array(
        'title' => 'HaPartizanim',
        'file' => './assets/cubes/HaPartizanim.png',
        $slides => array(
            'slide1' => './assets/pop-up/HaPartizanim-1.png',
            'slide2' => './assets/pop-up/HaPartizanim-2.png',
            'slide3' => './assets/pop-up/HaPartizanim-3.png',
            'slide4' => './assets/pop-up/HaPartizanim-4.png'
        )
    ),
    array(
        'title' => 'Toro House',
        'file' => './assets/cubes/Toro_House.png',
        $slides => array(
            'slide1' => './assets/pop-up/Toro_House-1.png',
            'slide2' => './assets/pop-up/Toro_House-2.png',
            'slide3' => './assets/pop-up/Toro_House-3.png'
        )
    ),
    array(
        'title' => 'HaAgana',
        'file' => './assets/cubes/HaAgana.png',
        $slides => array(
            'slide1' => './assets/pop-up/HaAgana-1.png',
            'slide2' => './assets/pop-up/HaAgana-2.png',
            'slide3' => './assets/pop-up/HaAgana-3.png',
            'slide4' => './assets/pop-up/HaAgana-4.png'
        )
    ),
    array(
        'title' => 'Har HaCarmel',
        'file' => './assets/cubes/Har_HaCarmel.png',
        $slides => array(
            'slide1' => './assets/pop-up/Har_HaKarmel-1.png',
            'slide2' => './assets/pop-up/Har_HaKarmel-2.png',
            'slide3' => './assets/pop-up/Har_HaKarmel-3.png',
            'slide4' => './assets/pop-up/Har_HaKarmel-4.png',
        )
    ),
    array(
        'title' => 'Kohvei Itzhak',
        'file' => './assets/cubes/Kohvei_Itzhak.png',
        $slides => array(
            'slide1' => './assets/pop-up/Kohvei_Itzhak-1.png',
            'slide2' => './assets/pop-up/Kohvei_Itzhak-2.png'
        )
    )
);

到目前为止,我无法使用的是

foreach($gallery as $key => $slides){
  foreach($slides as $key => $slide){
            $slide1 = $slide['slide1'];
            $slide2 = $slide['slide2'];
    echo $slide1, $slide2 . "<br/>";
  }
}   

感谢您的帮助,对不起英语不好。

1 个答案:

答案 0 :(得分:0)

首先,$slides => array(是无效的语法。我将假设您实际上是指'slides' => array(-如果是这样,下面的代码将使用implode()列出每个数组的所有属性。

foreach($gallery as $key => $slides){
    echo implode(', ', $slides['slides']) . "<br>";
}

如果您要为每张幻灯片做其他处理,请像这样循环遍历:

foreach($gallery as $key => $slides){
    foreach($slides['slides'] as $sub_key => $slide) {
        echo "<div>Key: $sub_key<br>Slide: $slide</div>";
    }
}