从多维数组中获取单个值

时间:2016-12-16 06:31:50

标签: php arrays multidimensional-array

PHP:

<?php 
print_r($details);
?>

嗨朋友们我在PHP代码中打印$ details的值,我在浏览器中输出的输出如下。

    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',sub_item和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;
}
?>

但是没有为我工作可以任何人请建议我如何从上面的数组中访问这些值,提前谢谢

3 个答案:

答案 0 :(得分: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 :(得分:1)

Foreach应该是

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

    }

答案 2 :(得分: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/>";
  }
}