0

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

我有以下代码:

$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

4 回答 4

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

对于任何有好处的...

于 2013-05-09T09:30:32.333 回答
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);
于 2013-05-09T09:35:19.417 回答
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"

但是,结果看起来有点奇怪,你确定这是你想要实现的吗?

于 2013-05-09T09:29:41.437 回答
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;
}

使用上面的代码,它将用于您的数组。

于 2013-05-09T09:29:56.700 回答