数组根据特定字段值创建组

时间:2015-02-11 07:15:57

标签: php arrays grouping element

我有以下数组

array
(
    [0] => Array
    (
        [market_id] => 10
        [competition_id] => 31        
    )

    [1] => Array
    (
        [market_id] => 10
        [competition_id] => 31        
    )

    [2] => Array
    (
        [market_id] => 11
        [competition_id] => 31        
    )

    [3] => Array
    (
        [market_id] => 11
        [competition_id] => 31        
    )

    [4] => Array
    (
        [market_id] => 11
        [competition_id] => 31        
    )
)

是否有一个函数可以从上面的输入创建下面的数组,或者我是否必须手动遍历数组并获得所需的结果?

array
(
    [0] => Array
    (
        [0] => Array
        (
            [market_id] => 10
            [competition_id] => 31        
        )
        [1] => Array
        (
            [market_id] => 10
            [competition_id] => 31        
        )
    )
    [1] => Array
    (
        [0] => Array
        (
            [market_id] => 11
            [competition_id] => 31        
        )
        [1] => Array
        (
            [market_id] => 11
            [competition_id] => 31        
        )
        [2] => Array
        (
            [market_id] => 11
            [competition_id] => 31        
        )        
    )
)

我想要的只是在 market_id 字段的基础上对数组元素进行分组。

2 个答案:

答案 0 :(得分:2)

另外,如果您不想使用vanilla PHP,可以使用ouzo-goodies

$array = array(
    0 => array(
        'market_id' => '10',
        'competition_id' => '31'
    ),
    1 => array(
        'market_id' => '10',
        'competition_id' => '31'
    ),
    2 => array(
        'market_id' => '11',
        'competition_id' => '31'
    ),
    3 => array(
        'market_id' => '11',
        'competition_id' => '31'
    ),
    4 => array(
        'market_id' => '11',
        'competition_id' => '31'
    )
);

$groupBy = Arrays::groupBy($array, Functions::extract()->market_id);

print_r($groupBy);

结果:

Array
(
    [10] => Array
        (
            [0] => Array
                (
                    [market_id] => 10
                    [competition_id] => 31
                )

            [1] => Array
                (
                    [market_id] => 10
                    [competition_id] => 31
                )

        )

    [11] => Array
        (
            [0] => Array
                (
                    [market_id] => 11
                    [competition_id] => 31
                )

            [1] => Array
                (
                    [market_id] => 11
                    [competition_id] => 31
                )

            [2] => Array
                (
                    [market_id] => 11
                    [competition_id] => 31
                )

        )

)

以下是ArraysFunctions的文档。

答案 1 :(得分:1)

没有捷径。使用market_id作为键构造一个新数组,然后删除临时键:

$result = [];
foreach ($array as $item) {
    $result[$item['market_id']][] = $item;
}
$result = array_values($result);