An exampleforgetting random value from arrays;
function array_random($arr, $num =1) {
shuffle($arr);
$r = array();
for($i =0; $i < $num; $i++) {
$r[] = $arr[$i];
}
return$num ==1? $r[0] : $r;
}
$a = array("apple","banana","cherry");
print_r(array_random($a));
print_r(array_random($a,2));
?>
cherry
Array
(
[0] => banana
[1] => apple
)
And exampleforgetting random value from assoc arrays;
function array_random_assoc($arr, $num =1) {
$keys = array_keys($arr);
shuffle($keys);
$r = array();
for($i =0; $i < $num; $i++) {
$r[$keys[$i]] = $arr[$keys[$i]];
}
return$r;
}
$a = array("a"=>"apple","b"=>"banana","c"=>"cherry");
print_r(array_random_assoc($a));
print_r(array_random_assoc($a,2));
?>
Array
(
[c] => cherry
)
Array
(
[a] => apple
[b] => banana
)
网友评论