SAHAR SAHAR - 1 month ago 15
PHP Question

How to combine two array by key?

I want to combine two array in one while group by key.
I have two different array with different values and I want to combine them in one array where if key match then add second arrays value in first array if not then create array with array 2's value.

Primary key in first array is [created_by] and in second array its [upgrade_by]
Array1 is

Array(
[0] => Array
(
[Customer] => Array
(
[created_by] => 5
[amount] => 199
[name] => First Cux
)

)

[1] => Array
(
[Customer] => Array
(
[created_by] => 1
[amount] => 199
[name] => Last Cux
)

)
)


Array 2 is

Array
(
[0] => Array
(
[0] => Array
(
[refund_amount] => 100
)

[Historycustomer] => Array
(
[upgrade_by] => 1
[Company] => First Company
)

)
[1] => Array
(
[refund_amount] => 250
)

[Historycustomer] => Array
(
[upgrade_by] => 3
[company] => Last Company
)

)


I need result like this

Array(
[0] => Array
(
[Customer] => Array
(
[created_by] => 5
[amount] => 199
[name] => First Cux


)

)

[1] => Array
(
[Customer] => Array
(
[created_by] => 1
[amount] => 199
[refund_mount]=>100
[name] => Last Cux
[company] => First Company
)

)

[2] => Array
(
[Customer] => Array
(
[created_by] => 3
[refund_mount]=>250
[company] => Last Company
)

)
)


Primary key in first array is [created_by] and in second array its [upgrade_by]

Answer Source

Code:

$a=[
    ['Customer'=>['created_by'=>5,'amount'=>199,'name'=>'First Cux']],
    ['Customer'=>['created_by'=>1,'amount'=>199,'name'=>'Last Cux']]
];
$b=[
    [['refund_amount'=>100],'Historycustomer'=>['upgrade_by'=>1,'company'=>'First Company']],
    [['refund_amount'=>250],'Historycustomer'=>['upgrade_by'=>3,'company'=>'Last Company']]
];

foreach($b as $b1){
    $index=array_search($b1['Historycustomer']['upgrade_by'],array_column(array_column($a,'Customer'),'created_by'));
    if($index!==false){
        $a[$index]['Customer']+=['created_by'=>$b1['Historycustomer']['upgrade_by'],'refund_amount'=>$b1[0]['refund_amount'],'company'=>$b1['Historycustomer']['company']];
    }else{
        $a[]=['Customer'=>['created_by'=>$b1['Historycustomer']['upgrade_by'],'refund_amount'=>$b1[0]['refund_amount'],'company'=>$b1['Historycustomer']['company']]];
    }
}
var_export($a);

Output:

array (
  0 => 
  array (
    'Customer' => 
    array (
      'created_by' => 5,
      'amount' => 199,
      'name' => 'First Cux',
    ),
  ),
  1 => 
  array (
    'Customer' => 
    array (
      'created_by' => 1,
      'amount' => 199,
      'name' => 'Last Cux',
      'refund_amount' => 100,
      'company' => 'First Company',
    ),
  ),
  2 => 
  array (
    'Customer' => 
    array (
      'created_by' => 3,
      'refund_amount' => 250,
      'company' => 'Last Company',
    ),
  ),
)