两个数组合并解决方案

WBOY
Freigeben: 2016-06-13 12:26:20
Original
804 Leute haben es durchsucht

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

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 "
Nach dem Login kopieren
";

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 />
Nach dem Login kopieren

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!