2011-06-15 113 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)函數來解析數組。