0

我正在尝试在 PHP 中合并 2 个数组

让我们举个例子

$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'
  ),
)

合并后我需要:

$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',
  ),
)

我需要的是避免重写该字段,我需要保留第一个数组中的所有值并添加第二个数组中的值。请记住,我在数组中有一个数组。

现在我在一个小的 Codeigniter 框架应用程序中尝试这种方式(array_merge 方式):

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'];

你知道更好的方法吗?棘手的是第二级数组,数组里面的数组。

PS:这个问题我还没有找到好的回复,抱歉,如果我遗漏了什么或者信息不清楚,欢迎提出任何问题

干杯

4

1 回答 1

1

尝试使用双 array_merge:

function merge_products($a, $b) {
    $merged = array_merge($b, $a);
    $merged['codes'] = array_merge($b['codes'], $a['codes']);

    return $merged;
}

http://codepad.org/gY29h814

于 2013-06-11T18:16:06.763 回答