繁体   English   中英

如何基于php中的键值对数组进行分组

[英]How to group array based on key values in php

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

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。

然后我将其作为两个不同的记录添加到db中


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
        )
)

您可以使用提取来创建动态数组,

/* 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
        )

)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM