PHP按前缀排序数组

时间:2017-12-24 18:11:34

标签: php arrays sorting

我有一些看起来像这样的数据:

[0] => clrack_64_a_0_0
[1] => clrack_64_a_2_0
[2] => clrack_64_b_0_0
[3] => clrack_64_b_2_0
[4] => clrack_64_c_0_0
[5] => clrack_64_c_2_0

或者它也可以是这样的:

[0] => hc17_10_64_a_2_0
[1] => hc17_10_64_b_2_0
[2] => hc17_10_64_b_2_1
[3] => hc17_10_64_c_2_0
[4] => hc17_10_64_d_2_0
[5] => hc17_10_64_e_2_0

我想对它进行排序,使它看起来像这样:

[0] => [
    [0] => clrack_64_a_0_0
    [1] => clrack_64_b_0_0
    [2] => clrack_64_c_0_0
],
[1] => [
    [0] => clrack_64_a_2_0
    [1] => clrack_64_b_2_0
    [2] => clrack_64_c_2_0
],

或者像这样:

[0] => [
    [0] => hc17_10_64_a_2_0
    [1] => hc17_10_64_b_2_0
    [2] => hc17_10_64_c_2_0
    [3] => hc17_10_64_d_2_0
    [4] => hc17_10_64_e_2_0
],
[1] => [
    [0] => hc17_10_64_b_2_1
],

希望有人可以帮助我

1 个答案:

答案 0 :(得分:0)

根据新要求,我想出了这个:

<?php

$arr = [
    '0'  => 'clrack_64_a_0_0',
    '1'  => 'clrack_64_a_2_0',
    '2'  => 'clrack_64_b_0_0',
    '3'  => 'clrack_64_b_2_0',
    '4'  => 'clrack_64_c_0_0',
    '5'  => 'clrack_64_c_2_0',
    '6'  => 'clrack_64_d_0_0',
    '7'  => 'clrack_64_d_2_0',
    '8'  => 'clrack_64_e_0_0',
    '9'  => 'clrack_64_e_2_0',
    '10' => 'clrack_64_f_0_0',
    '11' => 'clrack_64_f_2_0',
];

foreach( $arr as $value ){
    $new[] = [
        'orig'  => $value,
        'parts' => explode('_', $value)
    ];
}

foreach( $new as $x )
{
    $z = array_pop( $x['parts'] );
    $y = array_pop( $x['parts'] );
    $sorted[$z][$y][] = $x['orig'];
}

$sorted = array_combine(
    range(0, count($sorted)-1), 
    array_values($sorted)
);

foreach( $sorted as $k => $v )
{
    $n[$k] = array_combine(
        range(0, count($v)-1), 
        array_values($v)
    );
}

echo '<pre>';
print_r( $n );
echo '</pre>';