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

shuffle() doesn't work as expected with an associative array

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

$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"

¿shuffle 关联数组?这对我有用:

 function shuffle_assoc($array) {
    $keys = array_keys($array);
    shuffle($keys);
    foreach($keys as $key) {
        $new[$key] = $array[$key];
    }
    return $new;
}

使用:

Print_r(shuffle_assoc($my_array));

输入:

$my_array = Array
                (
                  [Nicaragua] => 62
                  [Mexico] => 50
                  [France] => 23
                 )

输出:

Array
(
    [France] => 23
    [Nicaragua] => 62
    [Mexico] => 50
)