为了账号安全,请及时绑定邮箱和手机立即绑定

PHP - 合并和组合数组

PHP - 合并和组合数组

PHP
蓝山帝景 2021-11-05 14:45:07
我有 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() 函数,但结果并不如预期
查看完整描述

1 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

如果您愿意将 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);

沙盒


我会发布输出,但它是相同的:) - 这就是重点。此外,我更喜欢尽可能少地引用这些键。它可以使维护代码更容易一些。


查看完整回答
反对 回复 2021-11-05
  • 1 回答
  • 0 关注
  • 163 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信