在php中合并多个数组

时间:2015-08-31 14:31:49

标签: php arrays

以下是返回的示例数组值:

这是第一个数组:

Array 1:

     0 => 
      name => Test name value
      desrciption => Test description value
      category => Test category value
      code_1 => IGEF001
      code_2 => IGGF001

     1 => 
      name => Test name value
      desrciption => Test description value
      category => Test category value
      code_1 => IGEF003
      code_2 => IGGF003

     2 => 
       name => Test name value
       desrciption => Test description value
       category => Test category value
       code_1 => IGEF004
       code_2 => IGGF004

这是第二个数组:

Array 2:

 0 => 
    return_code => IGEF003

 1 => 
   return_code => IGGF003

 2 => 
   return_code => IGGF004

 3 => 
   return_code => IGEF004

 4 => 
   return_code => IGGF001

 5 => 
   return_code => IGEF001

以下是我想要完成的事情:

 0 => 
   name => Test name value
   desrciption => Test description value
   category => Test category value
   code_1 => IGEF001
   code_2 => IGGF001
   select_code_1 => IGEF001 <-- Value coming from the second array
   select_code_2 => IGGF001 <-- Value coming from the second array


 1 => 
  name => Test name value
  desrciption => Test description value
  category => Test category value
  code_1 => IGEF003
  code_2 => IGGF003
  select_code_1 => IGEF003 <-- Value coming from the second array
  select_code_2 => IGGF003 <-- Value coming from the second array

 2 => 
  name => Test name value
  desrciption => Test description value
  category => Test category value
  code_1 => IGEF004
  code_2 => IGGF004
  select_code_1 => IGEF004 <-- Value coming from the second array
  select_code_2 => IGGF004 <-- Value coming from the second array

我希望这是足够的信息,如果您还需要,请告诉我。

2 个答案:

答案 0 :(得分:1)

好吧,如果我正确理解了您的问题,您希望在第二个数组中找到匹配的条目并将它们添加到第一个数组中。为了保持这个例子的简单,我假设匹配的条目总是存在的。如果不是这种情况,则需要添加if array_key_exists()或其他内容。

$result = array();
foreach ($array1 as $key => $value) {
   $result = $value;
   $result['select_code'] = $array2[$key]['return_code'];
}

我无法弄清楚的是应该找到结果中的第二个“select_code”条目。根据我的判断,将第一个条目映射到第二个数组中的条目的唯一方法是关键。如果您提供有关数据性质的更多信息,我将编辑我的答案。

答案 1 :(得分:0)

没关系我找到了解决方案。我做的是我在第一个数组的for循环中调用查询并链接值。因此,我没有使用两个独立的数组,而是决定创建一个单独的数组,这就是诀窍。

感谢您的帮助..