Php 按一列对子数组进行分组,使其与组中其他列的值以逗号分隔
Php 按一列对子数组进行分组,使其与组中其他列的值以逗号分隔,php,multidimensional-array,grouping,string-concatenation,delimited-text,Php,Multidimensional Array,Grouping,String Concatenation,Delimited Text,我有一个如下所示的数组: $array = [ ["444", "0081"], ["449", "0081"], ["451", "0081"], ["455", "2100"], ["469", "2100"] ]; 我需要分组为一个新数组,如下所示: array ( 0 => array ( 0 => '444,449,451', 1 => '0081', ), 1 => array
我有一个如下所示的数组:
$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)
应该有更优雅的解决方案,但我能想到的最简单的解决方案就是这个
// The data you have pasted in the question
$data = [];
$groups = [];
// Go through the entire array $data
foreach($data as $item){
// If the key doesn't exist in the new array yet, add it
if(!array_key_exists($item[1], $groups)){
$groups[$item[1]] = [];
}
// Add the value to the array
$groups[$item[1]][] = $item[0];
}
// Create an array for the data with the structure you requested
$structured = [];
foreach($groups as $group => $values){
// With the array built in the last loop, implode it with a comma
// Also add the 'key' from the last array to it ($group)
$structured[] = [implode(',', $values), $group];
}
我还没有测试过这个,但是类似的东西应该可以做到。这只需遍历给定的数组,并以结构化的方式收集所有条目(因此$groups
变量将包含共享一个键的每个组的一个数组条目,该键将对应于给定数组中每个项中的第二个项)。从那里,它只是关于重组它,以获得您所要求的格式
应该有更优雅的解决方案,但我能想到的最简单的解决方案就是这个
// The data you have pasted in the question
$data = [];
$groups = [];
// Go through the entire array $data
foreach($data as $item){
// If the key doesn't exist in the new array yet, add it
if(!array_key_exists($item[1], $groups)){
$groups[$item[1]] = [];
}
// Add the value to the array
$groups[$item[1]][] = $item[0];
}
// Create an array for the data with the structure you requested
$structured = [];
foreach($groups as $group => $values){
// With the array built in the last loop, implode it with a comma
// Also add the 'key' from the last array to it ($group)
$structured[] = [implode(',', $values), $group];
}
我还没有测试过这个,但是类似的东西应该可以做到。这只需遍历给定的数组,并以结构化的方式收集所有条目(因此$groups
变量将包含共享一个键的每个组的一个数组条目,该键将对应于给定数组中每个项中的第二个项)。从那里,它只是关于重组它,以获得您所要求的格式
写两个循环对于这个任务来说太费力了。使用
isset()
,在迭代时将临时键应用于输出数组。完成数据分组后,使用array\u values()
重新为输出编制索引
代码()
输出:
array (
0 =>
array (
0 => '444,449,451',
1 => '0081',
),
1 =>
array (
0 => '455,469',
1 => '2100',
),
)
编写两个循环对于这个任务来说太费力了。使用
isset()
,在迭代时将临时键应用于输出数组。完成数据分组后,使用array\u values()
重新为输出编制索引
代码()
输出:
array (
0 =>
array (
0 => '444,449,451',
1 => '0081',
),
1 =>
array (
0 => '455,469',
1 => '2100',
),
)
从字面上看,已经有几十个类似的问题得到了回答。搜索。现在已经有几十个类似的问题得到了回答。搜索。