2016-12-16 115 views
0

PHP:从多维数组获取单个值

<?php 
print_r($details); 
?> 

喜的朋友我打印的内容的$细节在PHP代码值和出把我在浏览器中得到如下。

Array ( 
     [0] => 
     Array ([item_id] => 8 [row] => [merchant_id] => 1 [discount] => [currentController] => store [price] => 60|Large [qty] => 1 [notes] => [cooking_ref] => Cooking reference 1 

      [ingredients] => Array ([0] => Ingredients 1) [require_addon_5] => 2 
      [sub_item] => Array (
       [5] => Array ([0] => 2|10|Addon Item 1|right [1] => 3|20|Addon Item 2|right) 
       [6] => Array ([0] => 2|10|Addon Item 1|right [1] => 3|20|Addon Item 2|right) 
       [7] => Array ([0] => 2|10|Addon Item 1|right [1] => 3|20|Addon Item 2|right) 
           ) 
      [addon_qty] => Array (
      [5] => Array ([0] => 1 [1] => 1) 
      [6] => Array ([0] => 1 [1] => 1) 
      [7] => Array ([0] => 1 [1] => 1) 
           ) 
      [require_addon_6] => 2 
      [require_addon_7] => 2 
      [two_flavors] => 
      [non_taxable] => 2 
      [addon_ids] => Array ([0] => 2 [1] => 3 [2] => 2 [3] => 3 [4] => 2 [5] => 3) 
      ) 
     ) 

现在我得到“ITEM_ID”,“cooking_ref”,分项目和addon_qty的值作为单个阵列。现在我想知道我们如何访问这些值。我已经提前尝试过类似

<?php 
print_r($details); 
echo "item_id : ".$details[0]['item_id']" <br />" 
echo "price : ".$details[0]['price']" <br />" 
echo "cooking_ref : ".$details[0]['cooking_ref']" <br />" 
echo "cooking_ref : ".$details[0]['cooking_ref']" <br />" 
echo "ingredients : "" <br />"; 

foreach($details['sub_item'] as $sub_item) 
{ 
    print_r($sub_item); 
    echo "<br /><br />"; 
    $sub_item_array_val +=1; 
} 
?> 

但没有workedout我可以在任何一个请建议我如何从上面的阵列存取权限这些值,由于

+0

尝试用'$ details [0] ['sub_item']替换$ details ['sub_item']' –

回答

0

以下是一种可能的方法 -

foreach($details as $detail) 
{ 
    echo "item_id: ".$detail['item_id']."<br/>"; 
    echo "price: ".$detail['price']."<br/>"; 
    echo "cooking_ref: ".$detail['cooking_ref']."<br/>"; 

    foreach($detail[$sub_item] as $sub_item) 
    { 
    echo "ingredients: <br/>"; 
    print_r($sub_item); 
    echo "<br/><br/>"; 
    } 

    foreach($detail[$addon_qty] as $addon_qty) 
    { 
    echo "ingredients: <br/>"; 
    print_r($addon_qty); 
    echo "<br/><br/>"; 
    } 
} 
1

试试这个:

$details = // your array; 

foreach($details as $detail) 
{ 
    echo $detail['item_id']; // will return 8 
    echo $detail['cooking_ref']; // will return Cooking reference 1 
} 
1

Foreach应该是

foreach($details[0]['sub_item'] as $sub_item) 
    { 
     print_r($sub_item); 
     echo "<br /><br />"; 

    }