简体   繁体   English

如何随机遍历PHP中嵌套关联数组的第一层?

[英]How to randomly loop through first layer of nested associative array in PHP?

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. 我当时在看PHP函数shuffle();,但我认为该函数通过混排所有层来弄乱整个数组。

You can randomly sort an array like this, it will keep the keys and the values 您可以像这样对数组进行随机排序,它将保留键和值

<?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);

You can get the keys using array_keys() . 您可以使用array_keys()获得密钥。 Then you can shuffle the resulting key array using shuffle() and iterate through it. 然后,您可以使用shuffle()来对结果键数组进行shuffle()并对其进行迭代。

Example: 例:

$keys = array_keys($myarray);
shuffle($keys);
foreach ($keys as $key) {
  var_dump($myarray[$key]);
}

According to my test, shuffle only randomizes 1 layer. 根据我的测试,随机播放只会随机分配1层。 try it yourself: 自己尝试:

<?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);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM