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.

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

You can get the keys using array_keys(). Then you can shuffle the resulting key array using shuffle() and iterate through it.

Example:

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

Comments

0

According to my test, shuffle only randomizes 1 layer. 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);
?>

2 Comments

shuffle does not preserve an array's keys. Please see the notes in the docs: php.net/manual/en/function.shuffle.php
I didn't see before i answered, you are using an associative array. That means you have named keys, IE $array['name'] = 'Bob'; $array['phone'] = '555-4202', instead of $array[0] = 'Bob'; $array[1] = '555-4202'. When you use shuffle, it mixes up the keys, so now $array['name']` might equal '555-4202'. This doesn't matter for numbered arrays, but for named array it will ruin your data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.