I have already asked this question once for a solution in Python:
python intersect of dict items
but I am now looking for the equivalent solution in PHP. Specifically I am using CakePHP 2.0 on the ConsoleShell.
I have an undetermined number of nests in an array and I want to loop over them like this:
$array = array(1 => array(1, 2, 3, 4), 2 => array(7, 8), n => array(n1, n2, n3))
foreach($array[1] as $k1 => $v1) {
foreach($array[2] as $k2 => $v2) {
foreach($array[n] as $kn => $vn) {
// do something with this combination
}
}
}
Bear in mind that n can be any number (the total number of nests), so I need code that allows for a dynamic number of nests.
Any ideas please?
Thanks
EDIT:
Just to clarify what I am after, if
$array = array(array(0, 1, 2, 3), array(0, 6, 7), array(0, 9, 10));
I want to end up with:
$array2 = array(
array(0, 0, 0),
array(0, 0, 9),
array(0, 0, 10),
array(0, 6, 0),
array(0, 6, 9),
...
array(3, 6, 10),
array(3, 7, 0),
array(3, 7, 9),
array(3, 7, 10)
);
however if $array has 4 array elements, then $array2 should have 4 elements on each line etc.
Edit:
After the OQ was updated it became clear, that not the depth is variable, but the element count. So we do not need recursion, but nested
foreachesThis gives the output as requested in the OQ
In short: We start with a result array, that has one element: an empty array. Now we cycle through the first level of the input array, in every step we replace all elements of the result array with a series of elements consiting of the original element with each of the members of our current array attached.
The first iteration replaces
The second iteration replaces
The third iteration replaces