如何在PHP中排序多维数组?

时间:2015-09-02 17:55:51

标签: php arrays sorting

您好我有类似的数组:

Array
(
    [0] => Array
        (
            [0] => Product_1
            [1] => Gold
        )

    [1] => Array
        (
            [0] => Product_1
            [1] => Silver
        )

    [2] => Array
        (
            [0] => Product_1
            [1] => Black
        )

    [3] => Array
        (
            [0] => Product_1
            [1] => Red
        )

    [4] => Array
        (
            [0] => Product_2
            [1] => Silver
        )

    [5] => Array
        (
            [0] => Product_2
            [1] => Gold
        )

    [6] => Array
        (
            [0] => Product_2
            [1] => Black
        )

如何将此数组排序为

[Product_1] => Array
          ( 
            [0] Silver
            [1] Black
            [2] Red
          )
[Product_2] => Array
          (
            [0] Silver
            [1] Gold
            [2] Black
          )

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

或者您只需使用array_walk作为

$result = [];
array_walk($array,function($v,$k)use(&$result){$result[$v[0]][] = $v[1];});
print_r($result);

输出:

Array
(
    [Product_1] => Array
        (
            [0] => Gold
            [1] => Silver
            [2] => Black
            [3] => Red
        )

    [Product_2] => Array
        (
            [0] => Silver
            [1] => Gold
            [2] => Black
        )

)

答案 1 :(得分:0)

只需循环浏览$array并将每个颜色值推送到以产品名称为键的$result数组。

$array = [
    ['Product_1', 'Gold'],
    ['Product_1', 'Silver'],
    ['Product_1', 'Black'],
    ['Product_1', 'Red'],
    ['Product_2', 'Silver'],
    ['Product_2', 'Gold'],
    ['Product_2', 'Black'],
];

$result = [];

foreach ($array as $values) {
    list ($product, $color) = $values;
    $result[$product][] = $color;
}

print_r($result);

输出:

Array
(
    [Product_1] => Array
        (
            [0] => Gold
            [1] => Silver
            [2] => Black
            [3] => Red
        )

    [Product_2] => Array
        (
            [0] => Silver
            [1] => Gold
            [2] => Black
        )

)