Home > Backend Development > PHP Tutorial > 两个数组合并解决方案

两个数组合并解决方案

WBOY
Release: 2016-06-13 12:26:20
Original
848 people have browsed it

两个数组合并
不太会描述,我举个例吧

array1
array1[0] = '1';
array1[1] = '2';

array2
array2[0] = '3';
array2[1] = '4';

想组合成

array[0]['arr1'] = '1'
array[0]['arr2'] = '3'

array[1]['arr1'] = '1'
array[1]['arr2'] = '4'

array[2]['arr1'] = '2'
array[2]['arr2'] = '3'

array[3]['arr1'] = '2'
array[3]['arr2'] = '4'
------解决思路----------------------
这是在求 笛卡尔积
------解决思路----------------------
用递归实现的,但是只能是两个数组,感觉这种方法有点笨

<br />$arr1=array(1,2);<br />$arr2=array(3,4);<br /><br />$res = test($arr1,$arr2,0,0);<br /><br />echo "<pre class="brush:php;toolbar:false">";<br />print_r($res);<br />echo "
Copy after login
";

function test($arr1,$arr2,$index1=0,$index2=0) {
static $result = array();
$tmp[]=$arr1[$index1];
$tmp[]=$arr2[$index2];
$result [] = $tmp;

if(($index1==count($arr1)-1) && ($index2==count($arr2)-1)){
return $result;
}else{
if($index2==count($arr2)-1){
$index1++;
$index2 = 0;
}else{
$index2++;
}
return test($arr1,$arr2,$index1,$index2);
}
}
/*
Array
(
[0] => Array
(
[0] => 1
[1] => 3
)

[1] => Array
(
[0] => 1
[1] => 4
)

[2] => Array
(
[0] => 2
[1] => 3
)

[3] => Array
(
[0] => 2
[1] => 4
)

)
*/

------解决思路----------------------
<br />$arr1 = array(1,2);<br />$arr2 = array(3,4);<br />$arr = array();<br /><br />for($i=0,$max1=count($arr1); $i<$max1; $i++){<br />    for($j=0,$max2=count($arr2); $j<$max2; $j++){<br />        $tmp = array();<br />        $tmp['arr1'] = $arr1[$i];<br />        $tmp['arr2'] = $arr2[$j];<br />        $arr[] = $tmp;<br />    }<br />}<br /><br />print_r($arr);<br />
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template