随机顺序的多维数组

Cud*_*dos 9 php

我想这样做,以便我的多维数组是随机顺序.你会怎么做?

// This is how the array looks like
print_r($slides);

Array
(
    [0] => Array
        (
            [id] => 7
            [status] => 1
            [sortorder] => 0
            [title] => Pants
        )

    [1] => Array
        (
            [id] => 8
            [status] => 1
            [sortorder] => 0
            [title] => Jewels
        )

    [2] => Array
        (
            [id] => 9
            [status] => 1
            [sortorder] => 0
            [title] => Birdhouse
        )

    [3] => Array
        (
            [id] => 10
            [status] => 1
            [sortorder] => 0
            [title] => Shirt
        )

    [4] => Array
        (
            [id] => 11
            [status] => 1
            [sortorder] => 0
            [title] => Phone
        )

)

// This how the result is if I use array_rand()
print_r(array_rand($slides, 5));

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
)

// This how the result is if I use shuffle()
print_r(shuffle($slides));

1
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 20

shuffle()是去这里的方式.它打印,1因为就地shuffle更改数组并返回一个布尔值,因为它在文档中写入:

成功时返回TRUE,失败时返回FALSE.

我建议还阅读以下文档array_rand():

从数组中挑选一个或多个随机条目,并返回随机条目的一个或多个.


如果使用内置函数,请务必阅读文档.不要只假设工作如何.我敢打赌,写这个问题比花时间更多.

  • 投票"不要只是假设他们如何工作",因为PHP功能不一致,因为地狱:) (2认同)
  • *Palm to head*当然!我误解了php.net上shuffle()的解释 (2认同)