Php将一个键中的两个数组元素组合在一起

时间:2017-03-12 19:47:47

标签: php arrays

嗨,我正在尝试将两个具有相同键的数组元素合并到一起。

array1 = array(0=>"1", 1=>"2", 2=>"3");
array2 = array(0=>"a", 1=>"b", 2=>"c");
foreach ($array1 as $origKey => &$subArray) 
  foreach ($array2[$origKey] as $key => $val) 
     $subArray[$key] = $val;

需要ouptut:

array(0=>"1a", 1=>"2b", 2=>"3c")

有人可以帮帮我吗?

5 个答案:

答案 0 :(得分:1)

使用以下函数组合值

function combineValues($a1, $a2){
    foreach ($a1 as $k => $v) 
         $r[$k] = $v . $a2[$k];
    return $r;
}

答案 1 :(得分:0)

你走了:

<?php

$array1 = array(0=>"1", 1=>"2", 2=>"3");
$array2 = array(0=>"a", 1=>"b", 2=>"c");

$sub = [];
foreach ($array1 as $key => $value) {
    array_push($sub, $value.$array2[$key]);
}

var_dump($sub);

- &GT;

array(3) {
  [0]=>
  string(2) "1a"
  [1]=>
  string(2) "2b"
  [2]=>
  string(2) "3c"
}

答案 2 :(得分:0)

{{1}}

答案 3 :(得分:0)

your this statement foreach ($array2[$origKey] as $key => $val) is wrong 
that part $array[$origkey] coz in foreach $key as $value this basically evaluates whole array so use this way ....

 <?php
 $array1 = array(0=>"1", 1=>"2", 2=>"3");
 $array2 = array(0=>"a", 1=>"b", 2=>"c");
 $array3 = array();
 for($i=0 ;$i<3 ;$i++)
{
  $array3[] = $array1[$i].$array2[$i];
}
foreach($array3 as $merge)
 {
     echo $merge."<br>";
 }
 ?>

答案 4 :(得分:0)

让我们明白,这只适用于任何长度的1维数组:

$concatted_array = array(); // the new array

// if the 2 arrays don't have te same lenght, get the largest array
$max_array_length = (count($array1) > count($array2)) ? count($array1) : count($array1);

// loop for the longest array
for ($i=0; $i <$max_array_length ; $i++) {

  if($i < count($array1) && $i < count($array2)) // if the element exist for both arrays
  {
    $concatted_array[$i] = $array1[$i].$array2[$i];

  } elseif($i < count($array1)) // if element only exists in $array1
  {
      $concatted_array[$i] = $array1[$i];

  } else // if element only exists in $array2
  { 

      $concatted_array[$i] = $array2[$i];
  }
}

var_dump($concatted_array);

这是输出:

array (size=3)
  0 => string '1a' (length=2)
  1 => string '2b' (length=2)
  2 => string '3c' (length=2)

现在这里有一些提示,以防万一你写的代码有错误:

  • 不要忘记变量之前的$
  • foreach应仅用于数组或对象,因此除非foreach ($array2[$origKey] as $key => $val)是数组或对象本身,否则不要$array2[$origKey]。请访问foreach documentation了解详情。