如何根据特定项目合并数组的行?

时间:2017-04-08 12:12:49

标签: php arrays

我有一个这样的数组:

$arr = [[1, "red"],
        [2, "blue"],
        [3, "yellow"],
        [1, "green"],
        [4, "green"],
        [3, "red"]];

这是预期的结果:

$output = [[1, ["red", "green"]],
           [2, ["blue"]],
           [3, ["yellow","red"]],
           [4, ["green"]]];

通过PHP可以做到这一点吗?

3 个答案:

答案 0 :(得分:0)

这个结构不是很方便,考虑到你可以使用索引号作为数组键,所以如果是我,我会坚持在我的答案中为数组$ temp创建的结构。无论如何,为了你想要的结果,你可以做到:

  $arr = [[1, "red"],
          [2, "blue"],
          [3, "red"],
          [1, "green"],
          [4, "green"],
          [2, "red"]];
  $res = array();
  $temp = array();
  $keys = array();
  foreach ($arr as $v) {
      $temp[$v[0]][] = $v[1];
  }
  foreach (array_keys($temp) as $k) {
      $res[]=array($k,$temp[$k]);
  }

另外,您的预期结果因为索引看起来更像:

$output = [[1, ["red", "green"]],
           [2, ["blue","red"]],
           [3, ["red"]],
           [4, ["green"]]];

答案 1 :(得分:0)

这可以通过缩减转换完成,然后在通过array_values语句构建所需输出后截断键。

//take only values (re-indexing 0..4)
$output = array_values(
  //build associative array with the value being a 'tuple'
  //containing the index and a list of values belonging to that index
  array_reduce($arr, function ($carry, $item) {

    //assign some names for clarity
    $index = $item[0];
    $color = $item[1];

    if (!isset($carry[$index])) {
      //build up empty tuple
      $carry[$index] = [$index, []];
    }

    //add the color
    $carry[$index][1][] = $color;

    return $carry;

  }, [])
);

答案 2 :(得分:0)

使用foreach循环和array_values函数的简短解决方案:

$arr = [[1, "red"], [2, "blue"], [3, "red"], [1, "green"], [4, "green"], [2, "red"]];

$result = [];
foreach ($arr as $pair) {
    list($k, $v) = $pair;
    (isset($result[$k]))? $result[$k][1][] = $v : $result[$k] = [$k, [$v]];
}
$result = array_values($result);