2016-11-06 66 views
-1

我需要一個數組轉換格式爲:轉換多維數組組織陣列在PHP

Array ( 
    [size] => P 
    [code] => Array ( 
     [0] => C01 
     [1] => B01 
     [2] = A02 
    ) 
) 

到多的人是這樣的:

Array ([size] => P [code] => C01) 
Array ([size] => P [code] => B01) 
Array ([size] => P [code] => A02) 

我會怎麼做,使用PHP代碼?

+1

使用循環。你有沒有嘗試過? – Eugene

回答

0

您需要遍歷code數組的項並將值推入新數組或新變量。

foreach($arr["code"] as $item){ 
    @$newArr[] = [ 
     "size" => "P", 
     "code" => $item 
    ]; 
} 
var_dump($newArr); 

校驗碼結果在demo

+0

如何通過foreach循環創建變量?這就是爲什麼我沒有使用'foreach'循環 –

+0

@AniketSahrawat正如你所看到的,我將值推入'$ newArr'數組中。 – Mohammad

0
$original = Array (
       'size' => 'P', 
       'code' => Array (
         0 => 'C01', 
         1 => 'B01', 
         2 => 'A02', 
       ) 
      ); 
$newArray = []; 
for($i=0; $i<count($original['code']); $i++){ 
    $newArray[$i]['size'] = $original['size']; 
    $newArray[$i]['code'] = $original['code'][$i]; 
} 

print_r($newArray); 

//陣列([0] =>數組([尺寸] => P [代碼] => C01)[1] =>數組( [size] => P [code] => B01)[2] => Array([size] => P [code] => A02))

您可以遍歷結果數組得到結果