0

I have a miltidimentional array like this:

Array ( [11] => Array ( [0] => 5 ) 
        [12] => Array ( [0] => 7 ) 
        [14] => Array ( [0] => 9 [1] => 10 [2] => 11 [3] => 25 ) 
      )

And would like to convert it like that:

Array ( [0] => Array ( [11] => 5 ) 
        [1] => Array ( [12] => 7 ) 
        [2] => Array ( [14] => 9 )
        [3] => Array ( [14] => 10)
        [4] => Array ( [14] => 11)
        [5] => Array ( [14] => 25)
      )

Do you have any idea how it could be done?

elfuego1
  • 10,318
  • 9
  • 28
  • 24
  • [What have you tried?](http://www.whathaveyoutried.com/) See [ask advice](http://stackoverflow.com/questions/ask-advice), please. – John Conde Mar 17 '13 at 20:40

2 Answers2

1

Bare minimum:

foreach($myArray as $a => $b)
  foreach($b as $c)
    $tmpArray[] = array($a => $c);
$myArray = $tmpArray; unset($tmpArray);

Working Example

animuson
  • 53,861
  • 28
  • 137
  • 147
Emissary
  • 9,954
  • 8
  • 54
  • 65
0
    <pre>
<?php

$arr = array();
$arr[11] = array(0, 1, 2);
$arr[12] = 3;
$arr[13] = array(4, 5);

print_r($arr);

$arr2 = array();

$x = 0;
$a = 0;

while ($x < 14) {// count() will fail with '3' but our numbers are at 11
    if (is_array($arr[$x])) {
        $p = 0;
        while ($p < count($arr[$x])) {// works here because index starts at 0 
            if (!is_null($arr[$x]))  {
                $arr2[$a++] = $arr[$x][$p];
            }
            $p ++;
        }
    }
    else {
        if (!is_null($arr[$x])) {
            $arr2[$a++] = $arr[$x];
        }
    }

    $x ++;
}

print_r($arr2);
?>
</pre>

Result:

Array
(
    [11] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
        )

    [12] => 3
    [13] => Array
        (
            [0] => 4
            [1] => 5
        )

)
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

im too tired so this is the max i can do now.. The problems:

while ($x < 14) {// count() will be '3' but our numbers are at 11

Maybe this code could be improved..

Marco Acierno
  • 14,682
  • 8
  • 43
  • 53