Shuffle an array in PHP

前端 未结 6 1703
悲&欢浪女
悲&欢浪女 2020-12-02 00:39

I have the following code:

image . \";
echo($url);
endforeach;
?>
相关标签:
6条回答
  • 2020-12-02 01:05

    Looks like you need to do shuffle( $bb['slides'] ).

    0 讨论(0)
  • 2020-12-02 01:17

    Display content at random order

    <?php
    $myContentList = array (
        'One',
        'Two',
        'Three',
        'Four'
    );
    shuffle ($myContentList);
    foreach ($myContentList as $displayAtRandomOrder) {
    echo '<div>' . $displayAtRandomOrder . '</div>';
    }
    ?>
    

    Display images at random order

    <?php
    $myImagesList = array (
        'one.png',
        'two.png',
        'three.jpg',
        'four.gif'
    );
    shuffle ($myImagesList);
    foreach ($myImagesList as $displayImagesAtRandomOrder) {
    echo '<img src="images/' . $displayImagesAtRandomOrder . '" width="200" height="40" border="0" />';
    }
    ?>
    
    0 讨论(0)
  • 2020-12-02 01:18
    <?php
    shuffle($bb['slides']);
    foreach($bb['slides'] as $b) {
        echo $url = "domain.com/" . $b->image . ";
    }
    ?>
    

    Check this blog for explanation with example.

    http://wamp6.com/php/str_shuffle-php/ Check for array shuffle

    0 讨论(0)
  • 2020-12-02 01:19
    shuffle($array_name); // will shuffle array
    

    http://www.php.net/manual/en/function.shuffle.php

    Also the foreach should be

    for($array_name as $array_item) {
    // do stuff
    }
    
    0 讨论(0)
  • 2020-12-02 01:20

    You probably shuffled the outer $bb array, when you should have done:

    shuffle($bb['slides']);
    foreach($bb['slides'] as $b):
    
    0 讨论(0)
  • 2020-12-02 01:26

    As $bb is an array of arrays, shuffle() won't randomise the sub-array, try shuffle on the nested array as follows:

    shuffle($bb['slides']);
    
    0 讨论(0)
提交回复
热议问题