开发者

Why does my PHP code not work?

Below is the code:

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

It is a two-dimensional array from a MySQL query, I want to shuffle the values whose keys are option1, option2, option3 and option4. But my code doesn't work. I can find the error by myself. Please suggest.开发者_开发技巧 Thanks in advance!


Just saw it:

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

shouldn't it be

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

You missed out the comparison in the for loop.


That's a very inefficient, bug-prone and unreadable way of doing that. You might want to try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜