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

Array create group on the basis of particular field value

我有以下数组

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 字段对数组元素进行分组。

此外,如果您不想在原版中使用他的方法 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
                )

        )

)

这是 Arrays and Functions 的文档。

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

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