根据一列值对子数组数据进行分组和合并 [英] Group and merge subarray data based on one column value
本文介绍了根据一列值对子数组数据进行分组和合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我下面的PHP代码中有一个数组,我想将此数组转换为按数据值分组。总是很难简化数组。
I have an array in PHP code below, and I want to convert this array to be grouped by data value. It's always hard to simplify arrays.
原始数组:
Array
(
[0] => Array
(
[date] => 2017-08-22
[AAA] => 1231
)
[1] => Array
(
[date] => 2017-08-21
[AAA] => 1172
)
[2] => Array
(
[date] => 2017-08-20
[AAA] => 1125
)
[3] => Array
(
[date] => 2017-08-21
[BBB] => 251
)
[4] => Array
(
[date] => 2017-08-20
[BBB] => 21773
)
[5] => Array
(
[date] => 2017-08-22
[CCC] => 3750
)
[6] => Array
(
[date] => 2017-08-20
[CCC] => 321750
)
)
下面是我想要的数组:
Array
(
[2017-08-22] => Array
(
[AAA] => 1231
[CCC] => 3750
)
[2017-08-21] => Array
(
[AAA] => 1172
[BBB] => 251
)
[2017-08-20] => Array
(
[AAA] => 1125
[BBB] => 21773
[CCC] => 321750
)
)
如果数据不存在,则具有空null值也是可以的。 [BBB] =>对于2017-08-22为NULL。
有人可以帮忙吗?预先感谢...
It is also ok to have empty null value if the data doesn't exist. [BBB] => NULL for 2017-08-22. Can anybody help? Thanks in advance...
推荐答案
一个简单的循环就可以做到这一点。
A simple loop should do this..
$group = [];
foreach ($data as $item) {
if (!isset($group[$item['date']])) {
$group[$item['date']] = [];
}
foreach ($item as $key => $value) {
if ($key == 'date') continue;
$group[$item['date']][$key] = $value;
}
}
这篇关于根据一列值对子数组数据进行分组和合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文