note 98742 deleted from function.shuffle by cmb
| From: | cmb@php.net | Date: | Mon, 22 Nov 2021 17:23:45 +0000 |
| Subject: | note 98742 deleted from function.shuffle by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217281@lists.php.net to get a copy of this message | ||
Note Submitter: m0gr14 at gmail dot com
----
This function shuffles an associative array recursive.
<?php
/**
* Shuffles an associative array recursive
* @author Mogria <m0gr14@gmail.com>
* @param array $array
* @return array
*
*/
function rec_assoc_shuffle($array)
{
$ary_keys = array_keys($array);
$ary_values = array_values($array);
shuffle($ary_values);
foreach($ary_keys as $key => $value) {
if (is_array($ary_values[$key]) AND $ary_values[$key] != NULL) {
$ary_values[$key] = rec_assoc_shuffle($ary_values[$key]);
}
$new[$value] = $ary_values[$key];
}
return $new;
}
?>
Example of use:
<?php
$array =
Array(
1,
Array(
1,
2,
3,
4,
Array(
1,
2,
3,
4,
5
)
),
2,
3,
Array(
0,
1,
Array(
1,
2,
3,
4,
Array(
1,
6,
5,
2,
1,
3
)
)
),
4,
5,
6,
7
);
$array = rec_assoc_shuffle($array);
echo '<pre>';
print_r($array);
echo '</pre>';
/*
Returns:
Array
(
[0] => 6
[1] => 5
[2] => Array
(
[0] => 1
[1] => 3
[2] => Array
(
[0] => 3
[1] => 1
[2] => 2
[3] => 4
[4] => 5
)
[3] => 2
[4] => 4
)
[3] => 3
[4] => Array
(
[0] => Array
(
[0] => 3
[1] => 1
[2] => 4
[3] => Array
(
[0] => 5
[1] => 1
[2] => 3
[3] => 6
[4] => 1
[5] => 2
)
[4] => 2
)
[1] => 1
[2] => 0
)
[5] => 2
[6] => 1
[7] => 4
[8] => 7
)
*/
?>