如何按列值对子数组进行分组? [英] How to group subarrays by a column value?
本文介绍了如何按列值对子数组进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数组
Array
(
[0] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => reterty
[description] => tyrfyt
[packaging_type] => PC
)
[1] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => dftgtryh
[description] => dfhgfyh
[packaging_type] => PC
)
[2] => Array
(
[id] => 97
[shipping_no] => 212755-2
[part_no] => ZeoDark
[description] => s%c%s%c%s
[packaging_type] => PC
)
)
如何按 id
对数组进行分组?是否有任何本机 php 函数可用于执行此操作?
How can I group the array by id
? Is there any native php functions are available to do this?
虽然这种方法有效,但我想使用 foreach
来做到这一点,因为使用上述方法我会得到重复的项目,这是我试图避免的?
While this approach works, I want to do this using a foreach
, since with the above I will get duplicate items, which I'm trying to avoid?
在上面的例子中 id
有 2 个项目,所以它需要在 id
On the above example id
have 2 items, so its need to be inside of the id
推荐答案
没有原生的,就用一个循环.
There is no native one, just use a loop.
$result = array();
foreach ($data as $element) {
$result[$element['id']][] = $element;
}
这篇关于如何按列值对子数组进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文