Asaf Hadad
Asaf Hadad

Reputation: 25

PHP loop through arrays inside array

Im trying to loop through an array that is made from a couple of arrays that each has 2 properties and another array with diffrent number of properties. im trying to output all the properties of the last array using 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'
        )
    )
);

what i have so far and is not working is

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

Thanks for the help and sorry for bad english.

Upvotes: 1

Views: 2839

Answers (1)

GrumpyCrouton
GrumpyCrouton

Reputation: 8620

First of all, $slides => array( is invalid syntax. I will assume you actually meant 'slides' => array( - if that's true, the following code will list all of the properties from each array using implode().

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

If you want to do additional processing for each slide, loop through like this:

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

Upvotes: 1

Related Questions