duancan5327 2013-06-11 17:51
浏览 11
已采纳

在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

  • 写回答

1条回答 默认 最新

  • dou6495 2013-06-11 18:16
    关注

    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;
    }
    

    http://codepad.org/gY29h814

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求