从一个阵列到另一个中添加项 [英] Add items from one array to another

查看:102
本文介绍了从一个阵列到另一个中添加项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

1)的第一阵列

 阵列(    [0] =>阵列(
              [code => code_1
              [值] => XXX
    [1] =>阵列(
              [code => code_2
              [值] => XXX
    [2] =>阵列(
              [code => code_3
              [值] => XXX

2)第二阵列

 阵列(    [0] =>阵列(
              [设置code => code_1
              [值] => XXX
    [1] =>阵列(
              [设置code => code_2
              [值] => XXX
    [2] =>阵列(
              [设置code => code_3
              [值] => XXX
    [3] =>阵列(
              [设置code => code_4
              [值] => XXX
    [4] =>阵列(
              [设置code => code_5
              [值] => XXX

如何添加两个缺少的项目( code_4 code_5 )的数组2至ARRAY1 ?

感谢您!

UPD。

对不起,我需要澄清的问题了一下。我需要的结果数组的样子:

 阵列(    [0] =>阵列(
              [code => code_1
              [值] => XXX
    [1] =>阵列(
              [code => code_2
              [值] => XXX
    [2] =>阵列(
              [code => code_3
              [值] => XXX
    [3] =>阵列(
              [code => code_4
              [值] => XXX
    [4] =>阵列(
              [code => code_5
              [值] => XXX


解决方案

 函数add(由$,$到)
{
 的foreach($作为从$关键=> $值)
 {
  如果($为[$关键] ==)
       $为[$关键] = $价值;
 }
 返回到$;
}

array_merge将是更好的方法,但是

I have two arrays:

1) The first array:

array(

    [0] => array(
              [code] => code_1
              [value] => xxx
    [1] => array(
              [code] => code_2
              [value] => xxx     
    [2] => array(
              [code] => code_3
              [value] => xxx     

2) The second array:

array(

    [0] => array(
              [settingcode] => code_1
              [value] => xxx
    [1] => array(
              [settingcode] => code_2
              [value] => xxx     
    [2] => array(
              [settingcode] => code_3
              [value] => xxx
    [3] => array(
              [settingcode] => code_4
              [value] => xxx     
    [4] => array(
              [settingcode] => code_5
              [value] => xxx    

How can add two missing items (code_4 and code_5) from array2 to array1?

Thank you!

UPD.

Sorry, I need to clarify the question a bit. I need the resulting array to look like:

array(

    [0] => array(
              [code] => code_1
              [value] => xxx
    [1] => array(
              [code] => code_2
              [value] => xxx     
    [2] => array(
              [code] => code_3
              [value] => xxx
    [3] => array(
              [code] => code_4
              [value] => xxx     
    [4] => array(
              [code] => code_5
              [value] => xxx 

解决方案

function add($from, $to)
{
 foreach($from as $key => $value)
 {
  if($to[$key] == "")
       $to[$key] = $value;
 }
 return $to;
}

array_merge would be the better way, however

这篇关于从一个阵列到另一个中添加项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆