2011-06-15 111 views
7

我想使它成为我的多维数组以随机顺序排列。你会怎么做?以随机顺序的多维数组

// 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 
+1

可能重复[在PHP中混排数组的第一级](http://stackoverflow.com/questions/21758260/shuffling-the-first-level-of-the-array-in-php) – 2014-02-13 17:02:19

回答

17

shuffle()是去这里的路。它打印1因为shuffle改变就地阵列,并返回一个布尔值,因为它是写在documentation

成功返回TRUE 失败FALSE

我建议也可以参考documentation of array_rand()

精选一个或多个随机条目出的阵列,的并返回键(或多个密钥)的随机条目


如果使用内置函数务必阅读文档。不要只是假设如何工作。我敢打赌,写这个问题需要更多的时间,而不是看这个问题。

+2

Up投票“不要只是假设他们是如何工作的”,因为PHP的功能是不一致的地狱:) – Scuzzy 2011-06-15 09:03:42

+2

*掌上电脑*当然!我误解了php.net中对shuffle的解释() – Cudos 2011-06-15 09:06:05

+0

我觉得这是一个愚蠢的评论,但我认为“衬衫”想在洗牌后保持它的“地位”。换句话说,只有第一个维度被洗牌了,对吧? – 2014-01-28 18:38:46

0

它工作完美。 print_r(shuffle($ slides)))给出TRUE的输出,因为shuffle的返回值是布尔值而不是数组。

看到这里的工作示例:http://codepad.org/B5SlcjGf

1

而不是

print_r(shuffle($slides)); 

shuffle($slides); 
print_r($slides); 

你看shuffle()洗牌就地

+1

感谢所有downvotes。尽管如此,评论什么是错的会很好 – mkilmanas 2017-07-19 08:43:14

1

我不知道怎么阵列你想让它显示,但你可以循环数组并使用p hp rand(0,arraylen)函数来解析数组。