按一列对子阵列进行分组,从组中的其他列创建逗号分隔值

时间:2017-08-30 16:02:18

标签: php multidimensional-array grouping string-concatenation delimited-text


我有一个看起来像这样的数组:

d3

我需要将其分组为一个新的数组,如下所示:

$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',
  ),
)

2 个答案:

答案 0 :(得分:2)

应该有更优雅的解决方案,但我能想到的最简单的解决方案就是这个。

// 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变量将包含共享键的每个组的数组条目,并且键将对应于给定的每个项目中的第2项数组)。从那里开始重组它以获得您所要求的格式。

http://php.net/manual/en/control-structures.foreach.php

答案 1 :(得分:0)

编写两个循环对于此任务来说太费力了。在迭代过程中,将isset()与临时键一起应用于输出数组。完成数据分组后,用array_values()重新为输出编制索引。

代码(Demo

$array = [
    ["444", "0081"],
    ["449", "0081"],
    ["451", "0081"],
    ["455", "2100"],
    ["469", "2100"]
];

foreach ($array as $row) {
    if (!isset($result[$row[1]])) {
        $result[$row[1]] = $row;  // first occurrence of group, save whole row
    } else {
        $result[$row[1]][0] .= ',' . $row[0];  // not first occurrence, concat first element in group
    }
}

输出:

array (
  0 => 
  array (
    0 => '444,449,451',
    1 => '0081',
  ),
  1 => 
  array (
    0 => '455,469',
    1 => '2100',
  ),
)