问题描述
我想从 json 数组中过滤数据 where $data['stock'] != 0
。我可以将条件检查放在 foreach 循环中吗?或者,有没有更好的方法来执行相同的操作?
foreach($json['items'] as $data)
{
if(!$data['stock'] == 0) {
echo 'Success';
}
}
解决方法
有很多方法可以实现您想要实现的目标。你的代码没有错。您也可以尝试使用 array_filter()
。
$json = [
"items" => [[
"name" => "Widget","stock" => 3
],[
"name" => "Foo","stock" => 0
],[
"name" => "Bar","stock" => 2
]]
];
$filtered_array = array_filter($json['items'],function($data){
return $data['stock'];
//Will get rid fo the Foo item because its stock is 0
});
var_dump($filtered_array);
// Will NOT contain the Foo item
预期输出:
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "Widget"
["stock"]=>
int(3)
}
[2]=>
array(2) {
["name"]=>
string(3) "Bar"
["stock"]=>
int(2)
}
}
这将过滤您的数组以仅包含值在 $data['stock']
中的那些项目。您不需要编写 != 0
,因为在 PHP 中,在这个特定的比较上下文中,0
被翻译为布尔值 false。