PHP - 合并和组合数组

我有 3 个数组,如下所示:


数组 1:


array 1: [

  0 => array[

    "product_id" => "a"

    "quantity_1" => "1"

  ]

  1 => array[

    "product_id" => "b"

    "quantity_1" => "2"

  ]

  2 => array[

    "product_id" => "c"

    "quantity_1" => "1"

  ]

]

数组 2:


array 2: [

  0 => array[

    "product_id" => "a"

    "quantity_2" => "1"

  ]

  1 => array[

    "product_id" => "d"

    "quantity_2" => "2"

  ]

]

我想要的结果是:


array 3: [

  0 => array[

    "product_id" => "a"

    "quantity_1" => "1"

    "quantity_2" => "1"

  ]

  1 => array[

    "product_id" => "b"

    "quantity_1" => "2"

  ]

  2 => array[

    "product_id" => "c"

    "quantity_1" => "1"

  ]

  3 => array[

    "product_id" => "d"

    "quantity_2" => "2"

  ]

]

我尝试使用 array_combine() 函数,但结果并不如预期


蓝山帝景
浏览 164回答 1
1回答

HUWWW

如果您愿意将 product_id 作为密钥,那么您可以这样做:$a = [  0 => [    "product_id" => "a",    "quantity_1" => "1"  ],  1 => [    "product_id" => "b",    "quantity_1" => "2"  ],  2 => [    "product_id" => "c",    "quantity_1" => "1"  ]];$b =  [  0 => [    "product_id" => "a",    "quantity_2" => "1"  ],  1 => [    "product_id" => "d",    "quantity_2" => "2"  ]]; print_r(      array_replace_recursive(             array_column($a, null, 'product_id'),             array_column($b, null, 'product_id')      ) );输出Array(    [a] => Array        (            [product_id] => a            [quantity_1] => 1            [quantity_2] => 1        )    [b] => Array        (            [product_id] => b            [quantity_1] => 2        )    [c] => Array        (            [product_id] => c            [quantity_1] => 1        )    [d] => Array        (            [product_id] => d            [quantity_2] => 2        ))沙盒您可以随时从结果中删除密钥,array_values如下所示: print_r(    array_values(      array_replace_recursive(             array_column($a, null, 'product_id'),             array_column($b, null, 'product_id')      )    ) );-注意- product_ids 在每个数组中必须是唯一的,这样才能工作。否则,您可以简单地使用 foreach 循环来完成。$c = [];foreach(array_merge($a,$b) as $v){    $k = $v['product_id'];    if(!isset($c[$k])){        $c[$k] = $v;    }else{        $c[$k] = array_merge($c[$k],$v);    }}print_r($c);沙盒我会发布输出,但它是相同的:) - 这就是重点。此外,我更喜欢尽可能少地引用这些键。它可以使维护代码更容易一些。
打开App,查看更多内容
随时随地看视频慕课网APP