0

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.

Community
  • 1
  • 1
khany
  • 1,167
  • 15
  • 33
  • This is not an exact duplicate! Not even close. Please re-read my question. – khany Jan 08 '12 at 19:34
  • 1
    What do you want the result to be? Perhaps you may want to explain what you're trying to accomplish, for those who don't understand the solution to your Python question. – BoltClock Jan 08 '12 at 20:00

1 Answers1

1
function dosomething($a) {
  if (is_array($a)) 
    foreach ($a as $aa)
      dosomething($aa)
  else {
    //do something
  }
}

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 foreaches

This gives the output as requested in the OQ

<?php
$array = array(array(0, 1, 2, 3), array(0, 6, 7), array(0, 9, 10));

$result=array(array());
foreach ($array as $a) {
  $oldresult=$result;
  $result=array();
  foreach ($oldresult as $or) {
    foreach($a as $aa) {
      $nr=$or;
      $nr[]=$aa;
      $result[]=$nr;
    }
  }
}

print_r($result);
?>

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

array() with array(0), array(1), array(2), array(3)

The second iteration replaces

array(0) with array(0,0), array(0,6), array(0,7)
array(1) with array(1,0), array(1,6), array(1,7)
...

The third iteration replaces

array(0,0) with array(0,0,0), array(0,0,9), array(0,0,10)
array(0,1) with array(0,1,0), array(0,1,9), array(0,1,10)
...
array(1,0) with array(1,0,0), array(1,0,9), array(1,0,10)
...
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92