0

I have a nested assocative array which might look something like this:

$myarray = array(
  ['tiger'] => array(
    ['people'], ['apes'], ['birds']
  ),
  ['eagle'] => array(
    ['rodents'] => array(['mice'], ['squirrel'])
  ),
  ['shark'] => ['seals']
);

How can I loop through the first layer (tiger, eagle, shark) in a random order and ensure that I cover them all in my loop? I was looking at the PHP function shuffle();, but I think that function messes up the whole array by shuffling all layers.

4

3 回答 3

2

您可以像这样对数组进行随机排序,它将保留键和值

<?php
$myarray = array(
  'tiger' => array(
    'people', 'apes', 'birds'
  ),
  'eagle' => array(
    'rodents' => array('mice', 'squirrel')
  ),
  'shark' => 'seals'
);

$shuffleKeys = array_keys($myarray);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
    $newArray[$key] = $myarray[$key];
}

print_r($newArray);
于 2012-12-27T18:03:40.303 回答
1

您可以使用array_keys(). shuffle()然后,您可以使用并遍历它来打乱生成的键数组。

例子:

$keys = array_keys($myarray);
shuffle($keys);
foreach ($keys as $key) {
  var_dump($myarray[$key]);
}
于 2012-12-27T18:06:32.693 回答
0

根据我的测试,shuffle 只会随机化 1 层。自己试试:

<?php
$test = array(
        array(1,2,3,4,5),
        array('a','b','c','d','e'),
        array('one','two','three','four','five')
    );
shuffle($test);
var_dump($test);
?>
于 2012-12-27T18:05:17.617 回答