PHP遍历多维数组

时间:2015-10-02 02:23:01

标签: php arrays

我有以下多维数组:

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

我一直试图这样做几个小时,但是我在一个非常混乱的圈子里走了一圈,有人能说明我怎么能这样做吗?

2 个答案:

答案 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/>";
  }
?>

答案 1 :(得分: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'];
     }
   }
 }