PHP multidimensional array keys combinations/combinatorics -
ok, have assignment php , appreciate assistance. so, let's have multidimensional array one:
$testarray = array(0 => array(10, 20, 30), 1 => array(50, 60, 70), 2 => array(80, 90, 100), . . . n => array("", "", "",) );
values in array irrelevant, matters array keys. in case, have 3 keys in each array element, when permutation finished, final result should this:
[0] => array ( [0] => 1 1 1 [1] => 2 1 1 [2] => 3 1 1 [3] => 1 2 1 [4] => 2 2 1 [5] => 3 2 1 [6] => 1 3 1 [7] => 2 3 1 . . . [n] => 3 3 3 )
in case of 4 array keys, final result should this:
[0] = array ( [0] => 1 1 1 1 [1] => 2 1 1 1 [2] => 3 1 1 1 [3] => 4 1 1 1 [4] => 1 2 1 1 . . . [n] => 4 4 4 4 )
i avoid recursion if possible.
im having problems visualizing whole looping process , initializing needed variables. appreciate help. thank you.
i made slight modifications original code in order make use amount of keys instead of array values, , added second function allow multi-dimensional array counted well.
<?php function everycombination($array) { $newarray = array(); for($keycount = 1; $keycount <= count($array); $keycount++){ $newarray[] = $keycount; } $arraycount = count($newarray); $maxcombinations = pow($arraycount, $arraycount); $returnarray = array(); $conversionarray = array(); foreach ($newarray $key => $value) { $conversionarray[base_convert($key, 10, $arraycount)] = $value; } ($i = 0; $i < $maxcombinations; $i++) { $combination = base_convert($i, 10, $arraycount); $combination = str_pad($combination, $arraycount, "0", str_pad_left); $returnarray[] = strtr($combination, $conversionarray); } return $returnarray; } function getcombos($array){ if(is_array($array[key($array)])){ $return = array(); foreach($array $subarray){ $return[] = everycombination($subarray); } }else{ $return = everycombination($array); } return $return; } $test = array(53,22,1233,45); echo '<pre>'; print_r(getcombos($test)); echo '</pre>';
all credit function , usage goes https://stackoverflow.com/a/14022357/2285345
Comments
Post a Comment