Kho*_*din 4 php arrays array-filter
为什么我不能在外面调用变量array_filter(),这是我的代码
class JsonSelect
{
public function jsonSource($jsonSource, $val){
$file_contents = file_get_contents($jsonSource);
if(!$file_contents){
throw new Exception('Invalid file name');
}
$json = json_decode($file_contents, true);
$q = $_POST['q'];
$filtered = $json;
if(strlen($q)) {
$filtered = array_filter($json, function ($key) use ($q) {
if (stripos($key[$val], $q) !== false) {
return true;
} else {
return false;
}
});
}
echo json_encode(array_slice(array_values($filtered), 0, 20));
}
}
Run Code Online (Sandbox Code Playgroud)
匿名函数内的变量范围仅在匿名函数内。
您需要从父作用域继承变量。您可以在有关匿名函数的 PHP 文档中找到有关它的更多详细信息(示例 #3)
这将改变这条线:
$filtered = array_filter($json, function ($key) use ($q) {
Run Code Online (Sandbox Code Playgroud)
进入这个:
$filtered = array_filter($json, function ($key) use ($q, $val) {
Run Code Online (Sandbox Code Playgroud)