[英]How to group array based on key values in php
I have an array. 我有一个数组。 And I have to sort this array and then have to separate it as different array. 我必须对这个数组进行排序,然后再将其分隔为不同的数组。
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
)
)
I did sorting using usort 我使用usort进行了排序
function sortByOrder($a, $b) {
return $a['brand_id'] - $b['brand_id'];
}
usort($product_details, 'sortByOrder');
I need to group this array based on brand_id. 我需要根据brand_id将此数组分组。
The expected output is. 预期的输出是。
The name of the array also brand id. 数组的名称也为品牌ID。
Then I will add it to db as two different records 然后我将其作为两个不同的记录添加到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
)
)
You can use extract to create dynamic array, 您可以使用提取来创建动态数组,
/* 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 . 工作演示 。
Output:- 输出:-
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.