Insert “element” among other “elements” of the array (loop) php

后端 未结 3 988
遥遥无期
遥遥无期 2021-01-29 11:35

my code causes the images to appear randomly within the page. But how to insert an \"element\" (in my case would be a div) between these images?



        
相关标签:
3条回答
  • 2021-01-29 12:11

    You would want something like this...

     $myImagesList = array (
        'image1.png',
        'image2.png',
        'image3.png',
        'image4.png'
     );
     shuffle ($myImagesList);
    
     $i = 0;
     foreach ($myImagesList as $img) {
    
        $i++;
    
        if ($i % 3 === 0) { /* show content */ }
    
        echo '<img src="/image/' . $img . '" width="200" height="140" border="0" />';
    
     }
    

    This will give you the content section every third iteration, no matter the size of the list.

    0 讨论(0)
  • 2021-01-29 12:21

    If you want to add a div(content) between those two pairs of images - add additional condition into your loop:

    ...
    for ($i=0; $i<4; $i++) {
        if ($i == 1) echo '<div>some content ...</div>';
        echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
    }
    
    0 讨论(0)
  • 2021-01-29 12:24

    Go with the most readable solution - the one that doesn't make you fall and debug later when changing something.

    $splitAtNumber = 2; // or dynamically use count($myImagesList) / 2 or ....
    
    // output first part of the array
    for ($i = 0; $i < $splitAtNumber; $i++) {
        echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
    }
    
    // Output your content
    echo 'content';
    
    // Output second part of the array
    for ($i = splitAtNumber; $i < count($myImagesList); $i++) {
        echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
    }
    
    0 讨论(0)
提交回复
热议问题