[英]PHP array_filter
$alllist = array(
"link" => $link,
"title" => $title,
"imgurl" => $imgURL,
"price" => $price,
"mname" => $merchantname,
"description" => $description,
);
$all[] = $alllist;
I am trying to filter the array $all
where mname
is a certain value, let's say 'Amazon'. 我正在尝试过滤数组
$all
,其中mname
是某个值,比如说'Amazon'。 How do I do that? 我怎么做?
I tried this, but it did not work: 我试过了,但是没有用:
reset($all);
$all_filter = array_filter($all, function(filter) use ($all) {
$key = key($all);
next($all);
return key($all) === 'Amazon';
});
I think this what you want: 我认为这是您想要的:
$name = 'Amazon';
$all_filter = array_filter($all, function (array $item) use ($name) {
return array_key_exists('mname', $item) && $item['mname'] === $name;
});
$all[] = array("link"=> 1, "title"=> 2, "imgurl"=> 3,
"price"=>4, "mname"=>'Amazon', "description"=>5);
$all[] = array("link"=> 1, "title"=> 2, "imgurl"=> 3,
"price"=>4, "mname"=>'Facebook', "description"=>5);
$filtered = array_filter($all, function($item) {
return $item['mname'] === 'Amazon';
});
var_dump($filtered);
array_filter()
will iterate over the array
for you. array_filter()
将为您遍历array
。 You don't need to call reset()
or next()
. 您不需要调用
reset()
或next()
。
You should look at the array_filter() documentation for more info and examples. 您应该查看array_filter()文档以获取更多信息和示例。
$all_filter = array_filter($all, function($item) {
return $item['mname'] === 'Amazon';
});
It looks like you're making it more complex than it needs to be. 看起来您正在使它变得比所需的更加复杂。 The callback should just return a boolean value.
回调应该只返回一个布尔值。 If you don't want to hard-code the value you want to filter by (eg
'Amazon'
), you can pass it into the callback with use
. 如果您不想对要过滤的值进行硬编码(例如
'Amazon'
),则可以use
将其传递到回调中。
$filter_value = 'Amazon';
$all_filter = array_filter($all, function($item) use($filter_value) {
// without use($filter_value), $filter_value will be undefined in this scope
return $item['mname'] == $filter_value;
});
Returning the boolean expression $item['mname'] == $filter_value;
返回布尔表达式
$item['mname'] == $filter_value;
will determine which items have mname
values that match the filter value, and those items will be included in the result. 将确定哪些项目具有与过滤器值匹配的
mname
值,并且这些项目将包含在结果中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.