2,"5+2"=>7,"5+9"=>14,"3+5"=>8,"4+6"=>10,"1+8"=>9,"2+7"=>9,-6ren">
gpt4 book ai didi

php - shuffle() 不能按预期使用关联数组

转载 作者:行者123 更新时间:2023-12-05 03:13:23 25 4
gpt4 key购买 nike

我想做一个测验,这是我的数组:

$questions = array("1+1"=>2,"5+2"=>7,"5+9"=>14,"3+5"=>8,"4+6"=>10,"1+8"=>9,"2+7"=>9,
"6+7"=>13,"9+3"=>12,"8+2"=>10,"5+5"=>10,"6+8"=>14,"9+4"=>13,"7+8"=>15,
"8+9"=>17,"4+8"=>12,"7+1"=>8,"6+3"=>9,"2+5"=>7,"3+4"=>7);

shuffle($questions);

foreach($questions as $key => $value) {
echo $key.' ';
}

但是,从上面的代码中,我得到如下输出:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 //Wrong!

为什么我会得到这个输出?我想得到每一个问题。我该如何获取?

最佳答案

来自 shuffle() 的手册(强调我的):

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

这是来自 comments 的关联数组的解决方案该页面的:

function shuffle_assoc(&$array) {
$keys = array_keys($array);

shuffle($keys);

foreach($keys as $key) {
$new[$key] = $array[$key];
}

$array = $new;

return true;
}

致谢:“ahmad at ahmadnassri dot com”

关于php - shuffle() 不能按预期使用关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30306476/

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