合并数组。第二个数组作为“列”

时间:2013-05-09 09:23:47

标签: php arrays loops

这是一个例子......

我有以下代码:

$a=array("a","b","c");
$b=array("1","2","3");

$c = array_merge($a,$b);

echo "<pre>";
var_dump($c); 
echo "</pre>";

给我一​​个输出:

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

我如何更改代码,以便它为我提供此输出:

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

有什么想法吗?

4 个答案:

答案 0 :(得分:6)

$c = array_map(function ($a, $b) { return "$a','$b"; }, $a, $b);

对于任何有益的事情......

答案 1 :(得分:1)

使用SPL的MultipleIterator:

$a = array("a","b","c");
$b = array("1","2","3");

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));

$c = array();
foreach($mi as $row) {
    $c[] = $row[0] . "','" . $row[1];
}

var_dump($c);

答案 2 :(得分:0)

如果两个数组的键始终处于奇偶校验状态,则可以执行类似

的操作
foreach ($a as $key => $value) {
    $newArray[] = "$value','{$b[$key]}";
}

var_dump($newArray);
// would output the below
array(3) {
[0]=>
  string(5) "a','1"
  [1]=>
  string(5) "b','2"
  [2]=>
  string(5) "c','3"

然而,结果看起来有点奇怪,你确定这是你想要达到的目标吗?

答案 3 :(得分:0)

$a=array("a","b","c");
$b=array("1","2","3");

if(count($a) > count($b)){
  foreach($a as $key => $value)
      $c[$key] = isset($b[$key])? $value.",".$b[$key] : $value;
} else {
    foreach($b as $key => $value)
      $c[$key] = isset($a[$key])? $a[$key].",".$value : $value;
}

使用上面代码为您的数组。