两个数组合并解决方案
程序员文章站
2022-05-07 15:48:25
...
两个数组合并
不太会描述,我举个例吧
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'
------解决思路----------------------
这是在求 笛卡尔积
------解决思路----------------------
用递归实现的,但是只能是两个数组,感觉这种方法有点笨
------解决思路----------------------
不太会描述,我举个例吧
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'
------解决思路----------------------
这是在求 笛卡尔积
------解决思路----------------------
用递归实现的,但是只能是两个数组,感觉这种方法有点笨
$arr1=array(1,2);
$arr2=array(3,4);
$res = test($arr1,$arr2,0,0);
echo "";";
print_r($res);
echo "
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
)
)
*/
------解决思路----------------------
$arr1 = array(1,2);
$arr2 = array(3,4);
$arr = array();
for($i=0,$max1=count($arr1); $i for($j=0,$max2=count($arr2); $j $tmp = array();
$tmp['arr1'] = $arr1[$i];
$tmp['arr2'] = $arr2[$j];
$arr[] = $tmp;
}
}
print_r($arr);
相关文章
相关视频