2

下面是代码:

function swap(&$a, &$b)
{
     list($a, $b) = array($b, $a);
}

for ($i=0; count($resultset);$i++)
{
    for($j=1;$j<5;$j++)
    {
         $k = rand(1, 4);
         swap($resultset[$i]["option".$j],$resultset[$i]["option".$k]); 
    }
}

它是来自 MySQL 查询的二维数组,我想对键为 option1、option2、option3 和 option4 的值进行洗牌。但是我的代码不起作用。我可以自己找到错误。请建议。提前致谢!

4

2 回答 2

10

刚看到:

for ($i=0; count($resultset);$i++)

不应该

for ($i=0; $i < count($resultset);$i++)

您错过了 for 循环中的比较。

于 2009-11-22T09:11:46.340 回答
4

这是一种非常低效、容易出错且不可读的方式。你可能想试试这个:

$optionKeys = array('option1', 'option2', 'option3', 'option4');
foreach ($resultSet as &$row) {
    # Get options
    $options = array_intersect_key($row, array_flip($optionKeys));
    # randomize
    shuffle($options);
    # re-assemble key=>value array
    $options = array_combine($optionKeys, $options);
    # assign back to $row
    $row = $options + $row;
}
于 2009-11-22T10:22:23.623 回答