2012-04-27 101 views
1

任何人都可以幫助我瞭解多維數組嗎?我有想隨機陣列裏面的陣列,因此,因此它的層次結構或存在的索引值將被從陣列的原始佈置改變和不同的,如:隨機php多維數組並獲取原始數組索引

這是原始陣列

Array(
    [0]=>Array(
      [title]  => 'Title 1' 
      [description] => 'description here' 
     ) 
    [1]=>Array(
      [title]  => 'Title 2' 
      [description] => 'another description here'   
     ) 
    [2]=>Array(
      [title]  => 'Title Here Again' 
      [description] => 'description here again'   
     ) 
) 

這將是上述陣列的原始結構,如果你隨便吧,讓我們說,這將是

這是隨機編列結果

Array(
     [0]=>Array(
       [title]  => 'Title 2' 
       [description] => 'another description here' 
      ) 
     [1]=>Array(
       [title]  => 'Title 3' 
       [description] => 'another description again'   
      ) 
     [2]=>Array(
       [title]  => 'Title 1' 
       [description] => 'description here'   
      ) 
    ) 

正如你所看到的,數組內部的值在不同位置被隨機化,現在的問題是我無法獲得如何從隨機數組中獲得像這樣的原始數組索引的確切邏輯。就像'標題1'的值一樣,它的原始索引是[0],並且在它被隨機化後它變成了[2],但我仍然希望'標題1'被分配給索引[0]。下面是我如何隨機陣列短的PHP代碼:

foreach (shuffleThis($rss->getItems()) as $item) { 

    foreach($item as $key=>$value){ 
     if($key=='title'){ 
       $title=$value; 
     } 
     if($key=='description'){ 
      $description=$value;  
     } 
    } 
} 
function shuffleThis($list) { 
    if (!is_array($list)) return $list; 

    $keys = array_keys($list); 
    shuffle($keys); 
    $random = array(); 
    foreach ($keys as $key) { 
    $random[] = $list[$key]; 
    } 
    return $random; 
} 

只想得到他們被隨機編key的原始數組索引。

謝謝!

回答

1

如果我理解正確的話,你要更改的元素的順序但保留了鑰匙。你可以做一個小的修改:

function shuffleThis($list) { 
    if (!is_array($list)) return $list; 

    $keys = array_keys($list); 
    shuffle($keys); 
    $random = array(); 
    foreach ($keys as $key) { 
     $random[$key] = $list[$key]; // CHANGE HERE that preserves the keys 
    } 
    return $random; 
} 
+0

哇!這是一個很好的答案,當我嘗試它時,我可以看到元素正在改變位置,但不是數組鍵。但我怎麼能得到像這樣[0]的關鍵索引號,裏面的零? – 2012-04-27 08:06:11

+0

不確定你在問什麼。如何獲得哪個密鑰,並給出什麼信息? – Jon 2012-04-27 08:15:00