我有3个不同的数组,其中包含一个常量(但未知)的项目数。
$array1 = array("orange", "banana", "plum");
$array2 = array("apple", "raspberry", "pineapple");
$array3 = array("kiwi", "tomato", "lemon");
我想将键相同的每个数组的值连接成一个巨型数组。我想要创建的数组如下。
$desired_array = array("orange,apple,kiwi", "banana,raspberry,tomato", "plum,pineapple,lemon");
我甚至不确定如何处理这个问题。我试过了
foreach ($array1 as $arr1) {
foreach ($array2 as $arr2) {
foreach ($array3 as $arr3) {
$arr .= $arr1 . "," . $arr2 . "," . $arr3 ."\n";
}
}
}
但是返回
orange,apple,kiwi
orange,apple,tomato
orange,apple,lemon
orange,raspberry,kiwi
orange,raspberry,tomato
orange,raspberry,lemon
orange,pineapple,kiwi
orange,pineapple,tomato
orange,pineapple,lemon
banana,apple,kiwi
banana,apple,tomato
banana,apple,lemon
banana,raspberry,kiwi
banana,raspberry,tomato
banana,raspberry,lemon
banana,pineapple,kiwi
banana,pineapple,tomato
banana,pineapple,lemon
plum,apple,kiwi
plum,apple,tomato
plum,apple,lemon
plum,raspberry,kiwi
plum,raspberry,tomato
plum,raspberry,lemon
plum,pineapple,kiwi
plum,pineapple,tomato
plum,pineapple,lemon
答案 0 :(得分:2)
尝试此解决方案确定数组的长度始终相同。
<?php
$array1 = array("orange", "banana", "plum");
$array2 = array("apple", "raspberry", "pineapple");
$array3 = array("kiwi", "tomato", "lemon");
$arr=array();
for($l=0;$l<count($array1);$l++)
{
$arr[$l]=$array1[$l].",".$array2[$l].",".$array3[$l];
}
print_r($arr);
/*o/p:Array ( [0] => orange,apple,kiwi [1] => banana,raspberry,tomato [2] => plum,pineapple,lemon )*/
?>
编辑:
如果您需要,请在 FOR EACH 循环
中<?php
$array1 = array("orange", "banana", "plum");
$array2 = array("apple", "raspberry", "pineapple");
$array3 = array("kiwi", "tomato", "lemon");
$arr2=array();
foreach($array1 as $key=>$value)
{
$arr2[$key]=$array1[$key].",".$array2[$key].",".$array3[$key];
}
print_r($arr2);
?>