简体   繁体   中英

Foreach looping within a foreach loop

I am trying to create a random 3 column grid, the rows can be 1 of 3 setups,

1) 3 x 1/3 width divs 2) 1 x 1/3 width div & 1 x 2/3 div 3) 1 x 2/3 width div & 1 x 1/3 div

I have these options stored in array, what I am then doing to make it random is,

shuffle($columns)

this creates a random selection from the array, I then loop of my main data array (the array that holds the content for the divs) and within that loop over the colunm array to spit out the front end HTML.

<div class="item-wrapper">

<?php 
    //$last = "";
    $columns = array(
        array('single', 'single', 'single'),
        array('double', 'single'),
        array('single', 'double')
    );  



?>

@foreach($portfolio as $item)

    @foreach($columns[0] as $k => $v)   
        <div class="item item--<?php echo $v; ?>">
            <?php echo $item['name']; ?>
        </div>

    @endforeach

@endforeach

However this seems to loop of my main data multilpe times, what I am wanting is to loop over the main data, and spit that data into a div that has a class from the columns array.

I want an output that will look something like this,

<div class="item item--single">Project 1</div>  
<div class="item item--double">Project 2</div>  
<div class="item item--single">Project 3</div>  
<div class="item item--single">Project 4</div>  
<div class="item item--single">Project 5</div>
<div class="item item--single">Project 6</div>  
<div class="item item--double">Project 7</div>
<div class="item item--double">Project 8</div>  
<div class="item item--single">Project 9</div>

is this possible?

To loop over the inner array, I would say you should use $item instead of $column[0] there (untested):

@foreach($portfolio as $item)

-->    @foreach($item as $k => $v)        
        <div class="item item--<?php echo $v; ?>">
            <?php echo $item['name']; ?>
        </div>

    @endforeach

@endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM