我正在尝试过滤将产生向下钻取列表的数组。 此数组是基于JSON构建的。
我的数组看起来像这样
Array
(
[0] => Array
(
[make] => somemake
[model] => somemodel
[variant] => somevariant
[fuel] => somefuel
[vehicle] => somedetailedinfo
)
[1] => Array
(
[make] => somemake
[model] => somemodel1
[variant] => somevariant1
[fuel] => somefuel1
[vehicle] => somedetailedinfo
)
[2] => Array
(
[make] => somemake
[model] => somemodel2
[variant] => somevariant2
[fuel] => somefuel
[vehicle] => somedetailedinfo
)
[3] => Array
(
[make] => somemake1
[model] => somemodel3
[variant] => somevariant3
[fuel] => somefuel1
[vehicle] => somedetailedinfo
)
)
我想用$make
设置的$_SERVER['QUERY_STRING']
来过滤此数组。
新数组应包含带有$make
标签的所有项目。
如何使用array_filter
执行此操作?
答案 0 :(得分:1)
这很简单。请注意,空合并(??
)> = 7.0。
$make = $_GET['make'] ?? 'Chevy';
$vehicles = [[
'make' => 'Ford',
'model' => 'F-150',
'variant' => '4x4',
'fuel' => 'diesel',
'vehicle' => [range(1,3)],
],[
'make' => 'Ford',
'model' => 'Escort',
'variant' => 'XS',
'fuel' => 'gas',
'vehicle' => [range(1,3)],
],[
'make' => 'Chevy',
'model' => 'Cobalt',
'variant' => 'ES',
'fuel' => 'electric',
'vehicle' => [range(1,3)],
],[
'make' => 'Ford',
'model' => 'Explorer',
'variant' => '2x4',
'fuel' => 'gas',
'vehicle' => [range(1,3)],
],[
'make' => 'Mini',
'model' => 'Cooper',
'variant' => 'eTurbo',
'fuel' => 'electro-diesel',
'vehicle' => [range(1,3)],
],];
print_r(array_filter($vehicles, function($vehicle) use($make) {
return $vehicle['make'] === $make;
}));
礼物:
Array
(
[2] => Array
(
[make] => Chevy
[model] => Cobalt
[variant] => ES
[fuel] => electric
[vehicle] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
)