Search code examples
phparraysarray-merge

How to merge 4 different keys and values arrays in PHP?


It seems to be a common question but I couldn't find any help...

I need to merge 4 arrays with different keys and values. So there are my 4 different arrays :

array(7) {
  ["id"]=>
  string(2) "32"
  ["title"]=>
  string(7) "Blettes"
  ["product_type_id"]=>
  string(2) "43"
  ["quantity"]=>
  string(4) "1.00"
  ["price"]=>
  string(4) "2.80"
  ["created_at"]=>
  string(19) "2011-09-03 11:31:35"
  ["proposition_vente"]=>
  string(1) "4"
}

array(4) {
  ["id"]=>
  string(2) "32"
  ["achat"]=>
  string(2) "47"
  ["total_price"]=>
  string(18) "131.59999999999994"
  ["total_vat"]=>
  string(18) "6.8619999999999965"
}

array(2) {
  ["id"]=>
  string(2) "32"
  ["exposition"]=>
  string(2) "46"
}

array(3) {
  ["id"]=>
  string(2) "32"
  ["sale_queue_id"]=>
  string(3) "163"
  ["exposition"]=>
  string(2) "56"
}

Into this one:

array(7) {
  ["id"]=>
  string(2) "32"
  ["title"]=>
  string(7) "Blettes"
  ["product_type_id"]=>
  string(2) "43"
  ["quantity"]=>
  string(4) "1.00"
  ["price"]=>
  string(4) "2.80"
  ["created_at"]=>
  string(19) "2011-09-03 11:31:35"
  ["proposition_vente"]=>
  string(1) "4"
  ["achat"]=>
  string(2) "47"
  ["total_price"]=>
  string(18) "131.5"
  ["total_vat"]=>
  string(18) "6.86"
  ["exposition"]=>
  string(2) "46"
  ["sale_queue_id"]=>
  string(3) "163"
  ["exposition"]=>
  string(2) "56"
}

I know I have to use the id to correctly merge them. I tried to use a combination of foreach() and array_merge() without success.

Any help is welcome :)


Solution

  • I figure it out with this:

    foreach ($totalProposition as $key => $value) {
    $test[$key]=array_merge($totalProposition[$key], $totalAchat[$key], $uniqueSale2[$key], $exposition2[$key]);    
    }
    

    Thank you for your help : )