Passing multiple arrays to a Cartesian function

103 views Asked by At

I need to pass multiple array's in an indexed format to a cartesain function in order to calculate every permutation. This works when the code is:

$count = cartesian(
Array("GH20"),
Array(1,3),
Array(6,7,8), 
Array(9,10)
);

I will not always know the length, number of arrays, or values so they are stored in another array "$total" which may look something like this:

Array ( 
    [0] =>  Array
            (
            [0] => 1
            [1] => 3
            ) 
    [1] => Array 
            (
            [0] => 6
            [1] => 7 
            [2] => 8
            ) 
    [2] => Array 
            ( 
            [0] => 9 
            [1] => 10 
            ) 
    )

I have tried implementing the user_call_back_function as per:

$count = call_user_func('cartesian', array($total));

However the array that then gets passed looks like this:

Array (
[0] => Array (
    [0] => Array (
        [0] => Array (
            [0] => 1
            [1] => 3
            [2] => 4
        )
            [1] => Array (
            [0] => 5
            [1] => 6
            [2] => 7
            [3] => 8
        )
            [2] => Array (
            [0] => 9
            [1] => 10
        )
        )
    )
)

Where am I going wrong, why is the array being buried further down in dimensions where it is not needed, and is this the reason why my cartesain function does no longer work?

Thanks, Nick

As requested, here is my cartesain function:

function cartesian() {
$_ = func_get_args();
if(count($_) == 0)
    return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
    foreach($c as $p)
        $r[] = array_merge(array($v), $p);
return $r;
}
1

There are 1 answers

1
robbmj On

why is the array being buried further down in dimensions where it is not needed?

Simply because you are wrapping an array in another array when calling call_user_func.

$count = call_user_func('cartesian', array($total));

Perhaps you meant this:

$count = call_user_func('cartesian', $total);

is this the reason why my cartesain function does no longer work?

I don't know, you have not posted your cartesain, just an arrat called cartesain

EDIT as op updated the question.

If you are using PHP 5.6 you should be able to use the splat operator.

call_user_func("cartesain", ...$total);

Disclaimer, I have not tested this.

Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator.