保留一个元素的顺序,但在php数组中洗牌另一个元素?

时间:2011-07-07 23:48:48

标签: php arrays shuffle

考虑一个如下所示的m维php数组:

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 )
)

请注意' stimid'元素是随机顺序但是'列表'元素是提升的。我只是在对这个阵列进行一次洗牌之后,以便列出'列表'元素仍然是连续的。例如,我喜欢新阵列的顺序是:

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 )
)

另请注意每个'列表中行的顺序'类型不需要保留他们的订单。

这可能是一个非常简单的问题,但我似乎无法解决它! 任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

不漂亮或高效但是:

$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);

输出:

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
        )

)

答案 1 :(得分:0)

你可以这样做:

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

适用于1层深度的嵌套数组。

答案 2 :(得分:0)

function cmp($a, $b) {
    if ($a['stimid'] == $b['stimid']) {
        return 0;
    }
    return ($a['stimid'] < $b['stimid']) ? -1 : 1;
}

uasort($array, 'cmp');