显示多维数组中的值

时间:2013-07-10 15:29:14

标签: php arrays multidimensional-array foreach

现在,这段代码显示了所有五种冰淇淋口味。我试图只显示有货的味道。

   <pre><?php

   $flavors = array();
   $flavors[] = array("name" => "Cookie Dough",      "in_stock" => true);
   $flavors[] = array("name" => "Vanilla",           "in_stock" => false);
   $flavors[] = array("name" => "Avocado Chocolate", "in_stock" => false);
   $flavors[] = array("name" => "Bacon Me Crazy",    "in_stock" => true);
   $flavors[] = array("name" => "Strawberry",        "in_stock" => false);

   foreach($flavors as $flavor) {


    echo $flavor["name"] . "\n";


  }

  ?></pre>

5 个答案:

答案 0 :(得分:1)

这应该可以解决问题。

foreach($flavors as $flavor) {
   if($flavor['in_stock'] === true)
       echo $flavor["name"] . "\n";
}

答案 1 :(得分:0)

您仍然可以使用foreach循环,但使用if语句

检查库存
foreach($flavors as $flavor) {
  if ($flavor["in_stock"])
    echo $flavor["name"] . "\n";
}

答案 2 :(得分:0)

替换

echo $flavor["name"] . "\n";

if ($flavor['in_stock']) {
  echo $flavor["name"] . "\n";
}

答案 3 :(得分:0)

foreach($flavors as $flavor)
{
   if ($flavor['in_stock'])
   {
       echo $flavor["name"] . "\n";
   }
}

答案 4 :(得分:0)

$flavorsInStock = array_filter($flavors, function($flavor) {
    return $flavor['in_stock'];
});

会给你一个新阵列,只有库存的味道。