retain order of one element but shuffle another in php array?
开发者_C百科Consider a m-dimensional php array that looks like this:
print_r($arr)
Array (
[0] => Array ( [stimid] => 6 [list] => L01 )
[1] => Array ( [stimid] => 3 [list] => L01 )
[2] => Array ( [stimid] => 2 [list] => L02 )
[3] => Array ( [stimid] => 5 [list] => L02 )
[4] => Array ( [stimid] => 1 [list] => L03 )
[5] => Array ( [stimid] => 4 [list] => L03 )
)
Notice that the 'stimid' element is in random order but the 'list' element is ascending. I'm simply after a shuffle of this array such that the 'list' elements remain contiguous. What I'd like the order of the new array to be, for example, is:
print_r($new_arr)
Array (
[0] => Array ( [stimid] => 1 [list] => L03 )
[1] => Array ( [stimid] => 4 [list] => L03 )
[2] => Array ( [stimid] => 3 [list] => L01 )
[3] => Array ( [stimid] => 6 [list] => L01 )
[4] => Array ( [stimid] => 2 [list] => L02 )
[5] => Array ( [stimid] => 5 [list] => L02 )
)
Also notice that the order of the rows within each 'list' type need not retain their order.
This may be a very simple problem, but I can't seem to solve it! Any help is appreciated.
Not pretty or efficient but:
$input = Array (
0 => Array ( 'stimid' => 6, 'list' => L01 ),
1 => Array ( 'stimid' => 3, 'list' => L01 ),
2 => Array ( 'stimid' => 2, 'list' => L02 ),
3 => Array ( 'stimid' => 5, 'list' => L02 ),
4 => Array ( 'stimid' => 1, 'list' => L03 ),
5 => Array ( 'stimid' => 4, 'list' => L03 ),
);
shuffle($input);
$list = array();
foreach ($input as $pos => $item)
{
$list[ $item['list'] ][] = $item;
}
$out = array();
foreach ($list as $item)
{
$out = array_merge($item, $out);
}
print_r($out);
Output:
Array
(
[0] => Array
(
[stimid] => 1
[list] => L03
)
[1] => Array
(
[stimid] => 4
[list] => L03
)
[2] => Array
(
[stimid] => 5
[list] => L02
)
[3] => Array
(
[stimid] => 2
[list] => L02
)
[4] => Array
(
[stimid] => 3
[list] => L01
)
[5] => Array
(
[stimid] => 6
[list] => L01
)
)
You can do it like this:
$new_arr = deep_shuffle_array($arr);
print_r($new_arr);
function deep_shuffle_array(array $array){
foreach($array as $k => $v){
shuffle($v);
$new_array[$k] = $v;
}
return $new_array;
}
Works for nested array's on 1 level deep.
function cmp($a, $b) {
if ($a['stimid'] == $b['stimid']) {
return 0;
}
return ($a['stimid'] < $b['stimid']) ? -1 : 1;
}
uasort($array, 'cmp');
精彩评论