需要使用相同的密钥对php数组进行分组

时间:2017-01-12 06:18:52

标签: php

我需要帮助分组我有这种数组的数组:

Array
(
    [0] => Array
        (
            [name] => rose
            [price] => 1
        )
[1] => Array
    (
        [name] => daisy
        [price] => 3
    )

[2] => Array
    (
        [name] => orchid
        [price] => 1
    )

[3] => Array
    (
        [name] => rose
        [price] => 2
    )

[4] => Array
    (
        [name] => daisy
        [price] => 3
    )

[5] => Array
    (
        [name] => orchid
        [price] => 1
    )

[6] => Array
    (
        [name] => rose
        [price] => 2
    )

[7] => Array
    (
        [name] => daisy
        [price] => 3
    )

[8] => Array
    (
        [name] => orchid
        [price] => 2
    )

)

我希望它像:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => rose
                    [price] => 1
                )
        [1] => Array
            (
                [name] => daisy
                [price] => 1
            )

        [2] => Array
            (
                [name] => orchid
                [price] => 1
            )

    )

[1] => Array
    (
        [0] => Array
            (
                [name] => rose
                [price] => 2
            )

        [1] => Array
            (
                [name] => daisy
                [price] => 2
            )

        [2] => Array
            (
                [name] => orchid
                [price] => 2
            )

    )

[2] => Array
    (
        [0] => Array
            (
                [name] => rose
                [price] => 3
            )

        [1] => Array
            (
                [name] => daisy
                [price] => 3
            )

        [2] => Array
            (
                [name] => orchid
                [price] => 3
            )

    )

 )

我的意思是想把它们分组在同一个地方"价格"价值出现。您可以从给定的数组中更好地理解它们。

1 个答案:

答案 0 :(得分:1)

$group = array();

foreach ( $array as $value ) {
    $group[$value['price']][] = $value;
}

var_dump($group);