PDA

View Full Version : Array of Arrays

knally1963
01-26-2010, 07:27 PM
hi all
i am trying to create a function that finds all the combinations of a given array and to store each combinatin in to a new array ie

array(1,2,3) would create seven new arrays (1),(2),(3),(1,2),(1,3),(2,3),(1,2,3),

my first function calculateNumberOfCombinations() works fine as this is the result when i use print_r() i get this;
Array ( [0] => Array ( [0] => 1 ) [1] => Array ( [0] => 2 ) [2] => Array ( [0] => 3 ) ) Array ( [0] => Array ( [0] => 1 [1] => 2 ) [1] => Array ( [0] => 1 [1] => 3 ) [2] => Array ( [0] => 2 [1] => 3 ) ) Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) ) which is an array of all my arrays as described above.
question is how do i separate each array from the large array.

the code contains a recursive function that i was toying with but no joy.

Very grateful for any help,advise or even counselling (im cracking up) .would be very much indebted to solver.:confused:
<?php
function calculateNumberOfCombinations(\$newArray,\$len)
{
if (\$len > count(\$newArray))
return 'error';
\$out = array();
if (\$len == 1) {
foreach (\$newArray as \$v)
\$out[] = array(\$v);
return \$out;
}
\$len--;
while (count(\$newArray) > \$len) {
\$b = array_shift(\$newArray);
\$c = calculateNumberOfCombinations(\$newArray, \$len);
foreach (\$c as \$v) {
array_unshift(\$v, \$b);
\$out[] = \$v;
}
}
return \$out;
}
\$numberOfCombos = array(1,2,3);
\$allArrays = array();
\$newArray=array();

for(\$count=2;\$count<=count(\$numberOfCombos); \$count++)
{
//counted at 2 as i dont have to worry about singles
\$newArray = calculateNumberOfCombinations(\$numberOfCombos, \$count);
//findArray(\$newArray);

// for testing purposes
print_r(\$newArray);
}

/*function findArray(\$newArray)
{

if (!is_array(\$newArray))
die('not array');
foreach (\$newArray as \$value) {
if (is_array(\$value)) {
findArray(\$value);

} else {
return(\$value);
//echo \$value.'';
//would need to create a new array with result from foreach loop how?
}

echo '<br />';
}
}
*/
?>