php php打乱数组二维数组、多维数组
php中的shuffle函数只能打乱一维数组,有什么办法快速便捷的打乱多维数组?手册上提供了
<?php function shuffle_assoc( $list ) { if (! is_array ( $list )) return $list ; $keys = array_keys ( $list ); shuffle( $keys ); $random = array (); foreach ( $keys as $key ) $random [ $key ] = $list [ $key ]; return $random ; } ?> |
上面这个是针对二维数组的!下面针对多维数组的乱序方法?尽可能的方便快速:
<?php function shuffle_assoc( $list ) { if (! is_array ( $list )) return $list ; $keys = array_keys ( $list ); shuffle( $keys ); $random = array (); foreach ( $keys as $key ) $random [ $key ] = shuffle_assoc( $list [ $key ]); return $random ; } ?> 以下函数也是出自php手册,可以打乱多维数组: |
/**
* Shuffles an associative array recursive
*
* @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
;
用知识的力量武装,把生活的绚烂点亮!