我一直在寻找谷歌的答案,但似乎无法找到一些万无一失的东西,并且不能真正把它弄得一团糟(进入生产网站).
我所拥有的是具有20多个过滤器的高级搜索,它返回包含ID和距离的数组.我需要做的是将这些结果随机播放,以便每次都以随机顺序显示.我现在出来的阵列是:
Array (
[0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
[1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
[2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
[3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
[4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
)
Run Code Online (Sandbox Code Playgroud)
我需要做的是每次都随机或按顺序进行,但保持id和距离对,即:
Array (
[4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
[1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
[3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
[2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
[0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
)
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
kar*_*m79 85
在保留键,值对的同时随机关联和非关联数组.还返回混洗数组,而不是将其移动到位.
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;
}
Run Code Online (Sandbox Code Playgroud)
测试用例:
$arr = array();
$arr[] = array('id' => 5, 'foo' => 'hello');
$arr[] = array('id' => 7, 'foo' => 'byebye');
$arr[] = array('id' => 9, 'foo' => 'foo');
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
Run Code Online (Sandbox Code Playgroud)
Ham*_*ish 17
从5.3.0开始,您可以:
uksort($array, function() { return rand() > rand(); });
Run Code Online (Sandbox Code Playgroud)
function shuffle_assoc($array)
{
$keys = array_keys($array);
shuffle($keys);
return array_merge(array_flip($keys), $array);
}
Run Code Online (Sandbox Code Playgroud)
在这里查看这个函数:
$foo = array('A','B','C');
function shuffle_with_keys(&$array) {
/* Auxiliary array to hold the new order */
$aux = array();
/* We work with an array of the keys */
$keys = array_keys($array);
/* We shuffle the keys */`enter code here`
shuffle($keys);
/* We iterate thru' the new order of the keys */
foreach($keys as $key) {
/* We insert the key, value pair in its new order */
$aux[$key] = $array[$key];
/* We remove the element from the old array to save memory */
unset($array[$key]);
}
/* The auxiliary array with the new order overwrites the old variable */
$array = $aux;
}
shuffle_with_keys($foo);
var_dump($foo);
Run Code Online (Sandbox Code Playgroud)
原帖在这里: https ://www.php.net/manual/en/function.shuffle.php#83007