-1

Ok, I've almost finished my script, but my output is not quite as supposed to be. Scripts task is to create all possible number combinations from the sum of all multidimensional array keys. Ive edited few scripts and combined in one script, but I cant seem to get desired output.

Ok, for example, lets say I have array like this one:

$test = array(0 => array(53, 22, 12),
    1 => array(94, 84, 94),
    2 => array(56, 45, 104)
);

Then I fetch array keys and store them in new array:

foreach ($test as $key => $row) {
    $output[] = count($row);          
}                                       
for($keycount = 1; $keycount <= count($output); $keycount++){
    $newarray[$keycount] = $keycount;
}

And then I count keys from newly created array, so the final combination is based on that number. In aforementioned example, I have 3 combinations, so the final array is supposed to look like this:

111
211
311
121
221
321
131
231
331
112
.
.
.
333

But with my script:

$arraycount = count($newarray);
$maxcombinations = pow($arraycount, $arraycount);
$return = array();
$conversion = array();
foreach ($newarray as $key => $value) {
    $conversion[] = $key;
}
for ($i = 0; $i < $maxcombinations; $i++) {
    $combination = base_convert($i, 10, $arraycount);
    $combination = str_pad($combination, $arraycount, "0", STR_PAD_BOTH);
    $return[$i][] = substr(strtr($combination, $conversion), 1, $arraycount);
}     
echo "<pre>".print_r($return, true)."</pre>";

I'm getting output like this:

Array
(
[0] => Array
    (
        [0] => 111
    )

[1] => Array
    (
        [0] => 121
    )

[2] => Array
    (
        [0] => 131
    )

[3] => Array
    (
        [0] => 211
    )

[4] => Array
    (
        [0] => 221
    )

[5] => Array
    (
        [0] => 231
    )

[6] => Array
    (
        [0] => 311
    )
Termininja
  • 6,620
  • 12
  • 48
  • 49
Greedy
  • 115
  • 12
  • 4
    Possible duplicate of [How to get all possible combinations of multidimensional array](http://stackoverflow.com/questions/15101494/how-to-get-all-possible-combinations-of-multidimensional-array) – mitkosoft Mar 24 '16 at 14:05
  • I dont think that you can classify that topic as duplicate, as he uses fixed keys and values. – Greedy Mar 24 '16 at 14:18
  • Apparently, you're using a bidimensional array `$return[$i][]` . If every entry has exactly one value, you can use instead `$return[$i] = ` or `$return[] = `. – LSerni Mar 24 '16 at 14:35

1 Answers1

0

You are using array like $return[$i][] thus you are getting your output as unexpected

Try

$return[$i] = substr(strtr($combination, $conversion), 1, $arraycount);

Instead of

$return[$i][] = substr(strtr($combination, $conversion), 1, $arraycount);
Shashank Shah
  • 2,077
  • 4
  • 22
  • 46