简体   繁体   English

foreach 循环中的数组执行错误:

[英]Error in Array execution in foreach loop :

Someone please help me correcting the errors in this code This was the code where i am trying to find the names of the icecreams in stock有人请帮我更正此代码中的错误 这是我试图查找库存冰淇淋名称的代码

<?php
$flavors = array();
$flavors[]=array("name" => "CD" , "in_stock" => true);
$flavors[]=array("name" => "V"  , "in_stock" => true);
$flavors[]=array("name" => "S"  , "in_stock" => false);

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

Use 采用

<?php
$flavors = array(
array("name" => "CD" , "in_stock" => true),
array("name" => "V"  , "in_stock" => true),
array("name" => "S"  , "in_stock" => false));

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

instead 代替

foreach($flavors as $flavor => value){

You are using multimentionals arrays, to use your aproach (=> value): 您正在使用multimentionals数组,以使用您的aproach(=> value):

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

PHP Arrays PHP数组

You have flat non-associative array, that means you don't need to iterate using $key => $value but just $item . 你有平坦的非关联数组,这意味着你不需要使用$key => $value迭代,而只需要$item

So in you case the fix is that simple: 所以在你的情况下修复很简单:

https://ideone.com/j7RMAH https://ideone.com/j7RMAH

...
// foreach ($flavors as $flavor => $value) {
foreach ($flavors as $flavor) {
...

foreach() - foreach will additionally assign the current element's key to the $key variable on each iteration foreach() - foreach还会在每次迭代时将当前元素的键分配给$key变量

foreach (array_expression as $key => $value)
    statement

Note: You can use any variable it's not necessary to use the variable with name $key 注意: 您可以使用任何变量,不必使用名为$key的变量

You are using the key for the condition $flavor["in_stock"] and same for the $flavor["name"] . 您正在使用条件$flavor["in_stock"]的密钥和$flavor["name"]的密钥。 You need to use $value which holding the current iteration array , correct use of foreach for your code is 你需要使用持有当前迭代array $value ,正确使用foreach为你的代码

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

Why iterate at all? 为什么要迭代? One can just filter an array with a condition: 可以使用条件过滤数组:

<?php

$flavors = [];
$flavors[] = ['name' => 'CD', 'in_stock' => true];
$flavors[] = ['name' => 'V',  'in_stock' => true];
$flavors[] = ['name' => 'S',  'in_stock' => false];

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

print_r($inStock);

$inStockFlavors = array_column($inStock, 'name');

print_r($inStockFlavors);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM