在PHP中合并2个数组的正确方法
问题描述:
I am trying to merge 2 arrays in PHP
let's take this example
$array_old = array (
'product_title' => 'LG Nexus 4 Android Smartphone 16GB Sim-Free',
'site' => 'http://www.amazon.co.uk/LG-Nexus-Android-...',
'title' => 'LG Nexus 4 Android Smartphone 16GB Sim-Free',
'price' => '300.00',
'delivery' => '0.00',
'codes' =>
array (
'mpn' => 'LG-E960',
),
)
$array_new = array (
'product_title' => 'Google Nexus 4 (UK 16GB Black)',
'price' => '319.99',
'brand' => 'Google Nexus 4 (UK, 16GB, Black)',
'attributes' => 'color: black',
'codes' =>
array (
'SKU' => '239049',
'mpn' => 'E960'
),
)
After merging I need to have:
$array_old = array (
'product_title' => 'LG Nexus 4 Android Smartphone 16GB Sim-Free',
'site' => 'http://www.amazon.co.uk/LG-Nexus-Android-...',
'title' => 'LG Nexus 4 Android Smartphone 16GB Sim-Free',
'price' => '300.00',
'delivery' => '0.00',
'attributes' => 'color: black',
'codes' =>
array (
'mpn' => 'LG-E960',
'SKU' => '239049',
),
)
What I need is to avoid rewriting the field, I need to keep all the values from the first array and just add the values from the second one. Remember that I have an array inside the array.
Now I am trying this way (array_merge way) in a small Codeigniter framework app:
if((isset($array_new['codes']))&&(isset($array_old['codes']))) $array_merged['codes'] = array_merge($array_new['codes'],$array_old['codes']);
elseif(isset($array_new['codes'])) $array_merged['codes'] = $array_new['codes'];
elseif((isset($scraper_content['codes']))) $array_merged['codes'] = $array_old['codes'];
if(isset($array_new)) $array_old = array_merge($array_new,$array_old);
if (isset($array_merged['codes'])) $array_old['codes'] = $array_merged['codes'];
Do you know a better way to do this? The tricky thing is the second level array, the array inside the array.
PS: I haven't find a good response to this question, sorry If I miss something or if the message is not clear, any questions are welcome
Cheers
答
Try with double array_merge:
function merge_products($a, $b) {
$merged = array_merge($b, $a);
$merged['codes'] = array_merge($b['codes'], $a['codes']);
return $merged;
}