1

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

   <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>
4

5 回答 5

1

这应该可以解决问题。

foreach($flavors as $flavor) {
   if($flavor['in_stock'] === true)
       echo $flavor["name"] . "\n";
}
于 2013-07-10T15:30:52.937 回答
0
$flavorsInStock = array_filter($flavors, function($flavor) {
    return $flavor['in_stock'];
});

将为您提供仅包含库存口味的新阵列。

于 2013-07-10T16:16:50.203 回答
0

您仍然可以使用 foreach 循环,但使用if语句检查库存

foreach($flavors as $flavor) {
  if ($flavor["in_stock"])
    echo $flavor["name"] . "\n";
}
于 2013-07-10T15:31:02.473 回答
0

代替

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

if ($flavor['in_stock']) {
  echo $flavor["name"] . "\n";
}
于 2013-07-10T15:31:25.900 回答
0
foreach($flavors as $flavor)
{
   if ($flavor['in_stock'])
   {
       echo $flavor["name"] . "\n";
   }
}
于 2013-07-10T15:31:46.927 回答