2013-03-17 138 views
0

我有一個miltidimentional陣列像這樣:PHP:插入多陣列鑰匙插入子陣列關鍵

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

,並想將它轉化這樣的:

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) 
    ) 

你有什麼想法如何可以做到?

+0

[你嘗試過什麼?](http://www.whathaveyoutried.com/)參見[問諮詢】(http://stackoverflow.com/questions/ask-advice),請。 – 2013-03-17 20:40:25

回答

1

裸露最小值:

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

Working Example

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> 

結果:

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太累了,所以這是最大我現在可以做.. 的問題:

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

也許這個代碼可以改善..