views:

111

answers:

2

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!

+10  A: 

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.

thephpdeveloper
+3  A: 

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