0

我有两个数组

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(0 => 'zero_b', 2 => 'two_b', 3 => 'three_b');
?>

我希望输出为:“零:zero_a zero_b。一:one_a one_b。等等......

所以我想要两个数组的值通过它们在数组中的外观来连接。我已经用 foreach 试过了,但是它将一个数组的每个值与另一个数组的每个值连接起来,所以我最终得到了 9 个输出......

4

2 回答 2

0

采用:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(0 => 'zero_b', 2 => 'two_b', 3 => 'three_b');
foreach(array_combine($array1,$array2) as $key=>$value) {

    echo substr($key,0,-2).":".$key." ".$value.".";

    //or
    //$k = explode("_",$key);
    //echo $k[0].":".$key." ".$value.".";

}
?>

也可以对两个以上的数组进行

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(0 => 'zero_b', 2 => 'two_b', 3 => 'three_b');
$array3 = array(0 => 'zero_c', 2 => 'two_c', 3 => 'three_c');
//........more array
foreach($array1 as $key=>$value) {  
    $k = explode("_",$value);
    echo $k[0].":".$array1[$key]." ".
                   $array2[$key]." ".
                   $array3[$key].". "
                   //.........more array item concat
                   ;
}
?>
于 2013-09-07T11:48:52.037 回答
0

有点啰嗦,但有效。

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(0 => 'zero_b', 2 => 'two_b', 3 => 'three_b');
?>

<?php
$shortestArray = (count($array1) < $array2)? $array1 : $array2; // Get the max number of elements
$newArray = array();
for($i = 0; $i < count($shortestArray); $i++){
    if(isset($array1[$i]) && isset($array2[$i])){
        array_push($newArray, $array1[$i]." ".$array2[$i]);
    }
}
$longestArray = ($shortestArray != $array1)? $array2 : $array1;
for($i = count($shortestArray)-1; $i < count($longestArray); $i++){
    array_push($newArray, $longestArray[$i]);
}

print_r($newArray);

?>
于 2013-09-07T11:57:35.870 回答