将二维数组的行按一列分组,并在每组中创建子数组[重复]

问题描述 投票:0回答:1

我有一个数组。我必须对这个数组进行排序,然后必须将其分离为不同的数组。

Array
(
    [0] => Array
        (
            [brand_id] => 1
            [product_type] => 1

        )

    [1] => Array
        (
            [brand_id] => 2
            [product_type] => 1

        )

     [2] => Array
        (
            [brand_id] => 1
            [product_type] => 1

        )
     [3] => Array
        (
            [brand_id] => 2
            [product_type] => 1

        )
)

我使用 usort 进行排序

function sortByOrder($a, $b) {
            return $a['brand_id'] - $b['brand_id'];
}

usort($product_details, 'sortByOrder');

我需要根据brand_id对该数组进行分组。

预期输出是。

数组的名称也是品牌 ID。

然后我会将其作为两条不同的记录添加到数据库中


Array
(
    [0] => Array
        (
            [brand_id] => 1
            [product_type] => 1

        )

    [1] => Array
        (
            [brand_id] => 1
            [product_type] => 1

        )
)

Array
(
    [0] => Array
        (
            [brand_id] => 2
            [product_type] => 1

        )

    [1] => Array
        (
            [brand_id] => 2
            [product_type] => 1
        )
)
php arrays multidimensional-array grouping sub-array
1个回答
0
投票

您可以使用extract创建动态数组,

/* after your sorting logic */
$result = [];
foreach ($product_details as $key => $value) {
    // grouping data as per brand id
    $result['brand_id'.$value['brand_id']][] = $value;
}
extract($result);
print_r($brand_id1);
print_r($brand_id2);

工作演示

输出:-

Array
(
    [0] => Array
        (
            [brand_id] => 1
            [product_type] => 1
        )

    [1] => Array
        (
            [brand_id] => 1
            [product_type] => 1
        )

)
Array
(
    [0] => Array
        (
            [brand_id] => 2
            [product_type] => 1
        )

    [1] => Array
        (
            [brand_id] => 2
            [product_type] => 1
        )

)
© www.soinside.com 2019 - 2024. All rights reserved.