2016-10-17 179 views
0

我有這樣的輸出:PHP循環多維關聯數組

enter image description here

我沒有任何想法,我怎樣才能讓我的數組是這樣的:

$array[ 

    0 => [ 
     'item_id' => 6, 
     'price' => "2311.00", 
     'qty' => 12, 
     'discount' => 0 
    ], 

    1 => [ 
     'item_id' => 7, 
     'price' => "1231.00", 
     'qty' => 1, 
     'discount' => 12 
    ], 

    2 => [ 
     'item_id' => 8, 
     'price' => "123896.00", 
     'qty' => 0, 
     'discount' => 24 
    ] 


] 

我已經開始了循環,但我真的不知道如何得到這種結構。

foreach($array as $wishlist){ 
     foreach($wishlist as $k => $v){ 

     } 
    } 
+0

顯示'$ wishlist'內容 – RomanPerekhrest

+0

該數組是屏幕截圖。謝謝。 – Rbex

回答

0

您應該必須使用for循環。

for($i=0;$i<count(youarray['item_id']);$i++) { 
    $wishlist[$i]['item_id'] = youarray['item_id'][$i]; 
    $wishlist[$i]['price'] = youarray['price'][$i]; 
    $wishlist[$i]['qty'] = youarray['qty'][$i]; 
    $wishlist[$i]['discount'] = youarray['discount'][$i]; 
} 

或用戶的foreach這樣

foreach(youarray['item_id'] as $key=>$val) { 
    $wishlist[$key]['item_id'] = $val; 
    $wishlist[$key]['price'] = youarray['price'][$key]; 
    $wishlist[$key]['qty'] = youarray['qty'][$key]; 
    $wishlist[$key]['discount'] = youarray['discount'][$key]; 
} 
2

可以遍歷的內外陣列來構建你的數據像這樣,這可以讓你進一步鍵添加到陣列中後 - 但不依賴於你內心的數組的鍵是連續

$wishlist = []; 
foreach ($array as $outerKey => $outerValue) { 
    foreach ($outerValue as $innerKey => $innerValue) { 
     $wishlist[$innerKey][$outerKey] = $innerValue; 
    } 
} 
+0

你是男人兄弟!難以理解... – Rbex

1

你的循環應該是這樣的:

foreach($array as $item => $wishlist){ 

     foreach($wishlist as $k => $v){ 

      $new_array[$k][$item] = $v; 

     } 
    }