我发现了很多这样的话题,但我的问题有点不同。我需要两个完全不同数组的笛卡尔坐标。第一个数组:
array(2) {
[0] => array(2) { ["value1"] => "some data1", ["value2"] => "some data2"]}
[1] => array(2) { ["value1"] => "some data3", ["value2"] => "some data4"]}
}
和第二个数组
array(3) {
[0] => array(3) { ["value3"] => "some data5", ["value4"] => "some data6", ["value5"] => "some data7"]}
[2] => array(3) { ["value3"] => "some data8", ["value4"] => "some data9", ["value5"] => "some data10"]}
[3] => array(3) { ["value3"] => "some data11", ["value4"] => "some data12", ["value5"] => "some data13"]}
}
有人知道如何从数组中得到笛卡尔积吗?
你不能尝试嵌套的for循环吗?
<?php
// NOTICE: Using PHP 5.4 array notation
/**
* Creates the cartisan product of 2 arrays
*
* @param Array $array1, the first array
* @param Array $array2, the second array
* @param Callable $operation, the function to call to merge the values from array 1 and 2
* @returns Array, the cartisian product representation of the 2 arrays with the $operation
* applied
*/
function CartisianArray($array1, $array2, $operation) {
$ret = [];
foreach($array1 as $row => $value1) {
foreach($array2 as $col => $value2) {
if (!isset($ret[$row])) {
$ret[$row] = [];
}
// Apply the $operation to the values
$ret[$row][$col] = $operation($value1, $value2);
}
}
return $ret;
}
然后调用它:
$result = CartisianArray($array1, $array2, function($v1, $v2) {
return $v1 + $v2; // you can define your own operation, here just merging values
});
你没有说明你想对这些值进行什么操作,所以我只是合并它们,但你可以很容易地改变它