繁体   English   中英

根据其键值在php中合并数组

[英]Merge array based on their key by value in php

我有这个数组:

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合并item从此数组创建一个新数组。

因此,最终输出如下:

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;
}

在线尝试!

<?php
function merge_array_by_key($arrays)
{
    $new_array = [];
    foreach($arrays as $array)
    {
        $new_array[$array["id"]] = $array;
    }
    return $new_array;
}

希望这有效!

您不必循环数组的每个项目。
如果使用array_column和array_intersect(_key),则只需要循环数组中的唯一ID。
我添加array_values只是为了确保您获得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);

https://3v4l.org/YJWuV



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

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"
    }
  }
}

输出:

 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" } } } 

https://3v4l.org/FLNcW

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM