Php 如何合并数组';是否基于特定项目创建行?

Php 如何合并数组';是否基于特定项目创建行?,php,arrays,Php,Arrays,我有这样一个数组: $arr = [[1, "red"], [2, "blue"], [3, "yellow"], [1, "green"], [4, "green"], [3, "red"]]; 这是预期的结果: $output = [[1, ["red", "green"]], [2, ["blue"]], [3, ["yellow","red"]],

我有这样一个数组:

$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可以做到这一点吗?

考虑到您可以使用索引号作为数组键,因此如果是我,我将坚持使用我的答案中为数组$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"]]];

这可以通过还原转换完成,然后在通过
array\u 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;

  }, [])
);

使用
foreach
循环和
array\u值
函数的简短解决方案:

$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);

是的,这在PHP中是可能的。一个简单的foreach循环就可以了。
[3,[“黄色”,“红色”]
-在您的输入上没有
黄色
。更新您的预期输出