gpt4 book ai didi

PHP 随机洗牌数组维护键 => 值

转载 作者:IT王子 更新时间:2023-10-29 00:52:25 25 4
gpt4 key购买 nike

我一直在谷歌上寻找答案,但似乎找不到万无一失的东西,而且真的不能把它搞砸(进入生产网站)。

我拥有的是一个包含 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 )
)

我需要做的是每次随机化或排序这些,但保持 id 和 distance 对,即:

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 )
)

谢谢:)

最佳答案

first user postshuffle下文档:

Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

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;
}

测试用例:

$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));

关于PHP 随机洗牌数组维护键 => 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4102777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com