PHP将数组元素添加到另一个数组中的每个元素

时间:2013-07-27 07:51:18

标签: php arrays

有没有办法将一个数组中的元素添加到另一个数组中的每个元素?

例如

$color = array("black", "white", "yellow");

$number = array("1", "2", "3");

我想要一个新阵列将它们全部组合起来,以便它们:

$colornumber = array("1black", "1white", "1yellow", "2black", "2white", "2yellow" etc.)

感谢。

3 个答案:

答案 0 :(得分:3)

$colornumber = array();
foreach ($numbers as $number){
     foreach($colors as $color){
         $colornumber[] = $number.$color;
     }
}

答案 1 :(得分:2)

<?php 
$colors = array("black", "white", "yellow");
$numbers = array("1", "2", "3");
$colors_numbers = array();

foreach ($numbers as $number):
   foreach ($colors as $color) {
    $colors_numbers[] = $number . $color;
   }
endforeach;

答案 2 :(得分:0)

$color = array("black", "white", "yellow");

$number = array("1", "2", "3");

function mergeArr($arr1,$arr2){

    if(is_array($arr1)&& is_array($arr2)){
$newArr = array();
foreach($arr1 as $val1){
    foreach($arr2 as $val2){
    $newArr[] = $val2.$val1;

    }
}
return $newArr;
}else{
return false;
}

}

print_r(mergeArr($color ,$number));

输出:

Array ( [0] => 1black [1] => 2black [2] => 3black [3] => 1white [4] => 2white [5] => 3white [6] => 1yellow [7] => 2yellow [8] => 3yellow )