-2

I found many topics like this but my problem is a little bit different. I need cartesian from two totally different arrays. first array:

array(2) {
[0] => array(2) { ["value1"] => "some data1", ["value2"] => "some data2"]}
[1] => array(2) { ["value1"] => "some data3", ["value2"] => "some data4"]}
}

and second array

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"]}
}

Does someone know how to get cartesian product from that arrays?

  • possible duplicate of [Finding cartesian product with PHP associative arrays](http://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays) – Steve Aug 06 '14 at 13:09
  • This sounds like you're asking us to do your homework for you. – Zombiesplat Aug 06 '14 at 14:14

1 Answers1

0

Can't you try a nested for loop?

<?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;
}

And then to call it:

$result = CartisianArray($array1, $array2, function($v1, $v2) {
             return $v1 + $v2; // you can define your own operation, here just merging values
});

You're not telling what operation you want with the values, so I'm just merging them but you can easily change that.

mTorres
  • 3,590
  • 2
  • 25
  • 36