2015-10-02 165 views
0

我有以下多維數組:PHP遍歷多維數組

Array 
( 
    [0] => 57950340 
    [1] => SALE-86 
    [2] => COMPLETE 
    [3] => 
    [4] => 333 
    [5] => 819 
    [6] => Array 
     ( 
     [0] => Array 
       ( 
       [number] => 1 
       [product] => Array 
           ( 
           [id] => 90316 
           [name] => CLASSIC COCKTAIL 
          ) 
       [quantity] => 1 
       [price_variation] => 1 
       [modifiers] => Array() 
       [notes] => 
       [unit_price] => 16.3636 
       [unit_tax] => 1.63636 
       ) 
     [1] => Array 
       ( 
       [number] => 2 
       [product] => Array 
          ( 
           [id] => 90316 
           [name] => CLASSIC COCKTAIL 
          ) 
       [quantity] => 1 
       [price_variation] => 1 
       [modifiers] => Array () 
       [notes] => 
       [unit_price] => 16.3636 
       [unit_tax] => 1.63636 
       ) 
     ) 
) 

我通過數組試圖循環,這樣我可以附和產品項目的名稱(在關鍵6陣列內舉行並用單價和初始訂單ID(初始數組的關鍵字0)分別回顯這些數據。

我一直在嘗試這樣做幾個小時,但我正在進行非常混亂的圈子,任何人都可以闡明我如何做到這一點?

回答

1
<?PHP 
    $multi_dimensional_array = [...]; // Your array here 

    $order_id = $multi_dimensional_array[0]; 
    $products_array = $multi_dimensional_array[6]; 
    foreach($products_array as $product) { 
    echo $product['product']['name']." costs ".$product['unit_price']; 
    echo " - ORDER: ".$order_id; 
    echo "<br/>"; 
    } 
?> 
0

使用foreachis_array()來檢查值是否爲數組,然後foreach訪問內部變量,最後您可以回顯它。

foreach($array as $key => $val) 
{ 
    if(is_array($val){ 
    foreach($val as $key2 => $val2) 
    { 
     //print_r($val2); to see the actual data you are accessing 
     echo "ID: " . $val2['product']['id']. ' Product Name: ' . $val2['product']['name'] . ' Quantity: ' . $val2['quantity']; 
    } 
    } 
}