我有一个数组,看起来像这样:
$array = [
["444", "0081"],
["449", "0081"],
["451", "0081"],
["455", "2100"],
["469", "2100"]
];
我需要分组为一个新数组,如下所示:
array (
0 =>
array (
0 => '444,449,451',
1 => '0081',
),
1 =>
array (
0 => '455,469',
1 => '2100',
),
)
我试过很多剧本,但都不成功。
function _group_by($array, $key) {
$return = array();
foreach($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}
$newArray = _group_by($array, 1); // (NO SUCCESS)
2条答案
按热度按时间r6vfmomb1#
应该有更优雅的解决方案,但我能想到的最简单的一个是这个。
我还没有测试过这个,但是类似的东西应该可以完成这个任务。它只是遍历给定的数组,并以结构化的方式收集所有条目(因此
$groups
变量将包含每个共享键的组的数组条目,并且键将对应于给定数组中每个条目中的第二个条目)。从那里开始,它只需要重新构造它,以获得您所请求的格式。http://php.net/manual/en/control-structures.foreach.php
cfh9epnr2#
编写两个循环对于此任务来说太费力了。请使用
isset()
,并在迭代时将临时键应用于输出数组。完成数据分组后,使用array_values()
重新索引输出。代码(Demo)
或者通过使用引用数组来避免结果数组中的临时关联数组。(Demo)
或者使用
array_reduce()
来享受函数式技术。(Demo)全部将输出: