英文:
Filtering and searching for strings by array_filter() function
问题
通过array_filter()函数,我可以筛选出年龄超过40岁的人,这返回了正确的答案。但是,如果我想对人们的姓名进行筛选,通过strpos()函数这个方法无法正常工作。例如,如果我想筛选包含词组sapi的姓名,答案应该包括sapi和rahmatsapi,但实际答案不是这样的。我尝试了其他函数,如strpbrk()函数,但它们也没有给出正确的答案。
如果我一定要使用array_filter()函数和字符串函数,正确的方法是什么?如果字符串函数没有这样的功能,有什么替代方案吗?谢谢。
英文:
I have a list of people's names and ages. Through function array_filter(), I can filter people who are over 40 years old, which returns the correct answer
But if I want to put a filter for the names of people, this issue does not work properly through the Strpos() function, for example, if I want to write the phrase sapi, the answer should include the names sapi and rahmatsapi, but the answer is not like that. I tried other functions such as the strpbrk() function, but they did not give the right answer.
$listL = [
['name' => 'sapi', 'age' => 49],
['name' => 'rahmatsapi', 'age' => 42],
['name' => 'neko', 'age' => 39]];
$filterUser = array_filter($listL, fn($user) => $user['age'] > 40);
$filterUser = array_filter($listL, fn($user) => strpos($user['name'], 'sapi'));
var_dump($filterUser);
If I definitely want to use array_filter()function and string functions, what is the correct way? If string functions do not have such capability, what is the alternative solution?
Thanks
答案1
得分: 0
在我的测试中,它工作正常。我相信这是因为 strpos
需要使用 ===
来检查,而不是 ==
。
$listL = [
['name' => 'sapi', 'age' => 49],
['name' => 'rahmatsapi', 'age' => 42],
['name' => 'neko', 'age' => 39]
];
$filterUserAge = array_filter($listL, function ($user) {
if ($user['age'] > 40) {
return $user;
}
});
$filterUserName = array_filter($listL, function ($user) {
$pos = strpos($user['name'], 'sapi');
$achou = false;
if ($pos === false) {
return $achou;
} else {
$achou = true;
return $user;
}
});
print_r($filterUserName);
祝好!
英文:
here in my test it work. I believe that is cause strpos need be check with === rather then ==
$listL = [
['name' => 'sapi', 'age' => 49],
['name' => 'rahmatsapi', 'age' => 42],
['name' => 'neko', 'age' => 39]];
$filterUserAge = array_filter($listL, function ($user){
if($user['age'] > 40){
return $user;
}
});
$filterUserName = array_filter($listL, function($user){
$pos = strpos($user['name'], 'sapi');
$achou =false;
if($pos === false){
return $achou;
}else{
$achou = true;
return $user;
}
});
print_r($filterUserName);
Regards
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论