php中基于键值的合并数组

php中基于键值的合并数组,php,arrays,Php,Arrays,我有一个数组: Array ( [0] => Array ( [id] => 99 [fruit] => Apple [color] => Green ) [1] => Array ( [id] => 99 [fruit] => Apple [col

我有一个数组:

Array
(
    [0] => Array
        (
            [id] => 99
            [fruit] => Apple
            [color] => Green
        )
    [1] => Array
        (
            [id] => 99
            [fruit] => Apple
            [color] => Red
        )
    [2] => Array
        (
            [id] => 555
            [fruit] => Banada
            [color] => Yellow
        )
)
我需要通过按
id
合并项,从这个数组创建一个新数组

因此,最终输出如下所示:

Array
(
    [99] => Array
        (
            [id] => 99
            [fruit] => Apple
            [color] => Green
        ),
        (
            [id] => 99
            [fruit] => Apple
            [color] => Red
        )
    [555] => Array
        (
            [id] => 555
            [fruit] => Banada
            [color] => Yellow
        )
)

谢谢。

您应该创建一个新数组来保存结果,并迭代输入,将每个元素添加到新数组中。注意PHP是如何自动创建子数组的

$output = array();
foreach($input as $fruit){
    $output[$fruit['id']][] = $fruit;
}

您不必循环数组中的每个项。
如果使用array\u column和array\u intersect(\u key),则只需循环数组中的唯一ID。
我将array_值添加到中只是为了确保获得0个索引数组,但如果这不重要,那么可以将其删除

$ids = array_column($arr, "id");

Foreach(array_unique($ids) as $id){
    $new[$id] = array_values(array_intersect_key($arr, array_intersect($ids, [$id])));
}
Var_dump($new);



或者,您可以通过在“颜色”上添加另一个array_列来获得更精简的输出

这将产生:

array(2) {
  [99]=>
  array(2) {
    ["fruit"]=>
    string(5) "Apple"
    ["color"]=>
    array(2) {
      [0]=>
      string(5) "Green"
      [1]=>
      string(3) "Red"
    }
  }
  [555]=>
  array(2) {
    ["fruit"]=>
    string(6) "Banana"
    ["color"]=>
    array(1) {
      [0]=>
      string(6) "Yellow"
    }
  }
}

尝试在数据中循环,并根据id创建新数组。
$new\u数组[$item['id']][]=$item
。您可以使用foreach通过
foreach($data as$item)
在数据中循环。
$ids = array_column($arr, "id");

Foreach(array_unique($ids) as $id){
    $temp = array_values(array_intersect_key($arr, array_intersect($ids, [$id])));
    $new[$id] = ['fruit' => $temp[0]['fruit'], 'color' => array_column($temp, "color")];
}
Var_dump($new);
array(2) {
  [99]=>
  array(2) {
    ["fruit"]=>
    string(5) "Apple"
    ["color"]=>
    array(2) {
      [0]=>
      string(5) "Green"
      [1]=>
      string(3) "Red"
    }
  }
  [555]=>
  array(2) {
    ["fruit"]=>
    string(6) "Banana"
    ["color"]=>
    array(1) {
      [0]=>
      string(6) "Yellow"
    }
  }
}