簡體   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