如何根据php

时间:2019-07-08 14:26:16

标签: php arrays sorting

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

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

1 个答案:

答案 0 :(得分: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);

Working Demo

输出:-

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
        )

)