使用array_filter()函数进行字符串的过滤和搜索

huangapple go评论85阅读模式
英文:

Filtering and searching for strings by array_filter() function

问题

通过array_filter()函数,我可以筛选出年龄超过40岁的人,这返回了正确的答案。但是,如果我想对人们的姓名进行筛选,通过strpos()函数这个方法无法正常工作。例如,如果我想筛选包含词组sapi的姓名,答案应该包括sapirahmatsapi,但实际答案不是这样的。我尝试了其他函数,如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.

  1. $listL = [
  2. ['name' => 'sapi', 'age' => 49],
  3. ['name' => 'rahmatsapi', 'age' => 42],
  4. ['name' => 'neko', 'age' => 39]];
  5. $filterUser = array_filter($listL, fn($user) => $user['age'] > 40);
  6. $filterUser = array_filter($listL, fn($user) => strpos($user['name'], 'sapi'));
  7. 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 需要使用 === 来检查,而不是 ==

  1. $listL = [
  2. ['name' => 'sapi', 'age' => 49],
  3. ['name' => 'rahmatsapi', 'age' => 42],
  4. ['name' => 'neko', 'age' => 39]
  5. ];
  6. $filterUserAge = array_filter($listL, function ($user) {
  7. if ($user['age'] > 40) {
  8. return $user;
  9. }
  10. });
  11. $filterUserName = array_filter($listL, function ($user) {
  12. $pos = strpos($user['name'], 'sapi');
  13. $achou = false;
  14. if ($pos === false) {
  15. return $achou;
  16. } else {
  17. $achou = true;
  18. return $user;
  19. }
  20. });
  21. print_r($filterUserName);

祝好!

英文:

here in my test it work. I believe that is cause strpos need be check with === rather then ==

  1. $listL = [
  2. ['name' => 'sapi', 'age' => 49],
  3. ['name' => 'rahmatsapi', 'age' => 42],
  4. ['name' => 'neko', 'age' => 39]];
  5. $filterUserAge = array_filter($listL, function ($user){
  6. if($user['age'] > 40){
  7. return $user;
  8. }
  9. });
  10. $filterUserName = array_filter($listL, function($user){
  11. $pos = strpos($user['name'], 'sapi');
  12. $achou =false;
  13. if($pos === false){
  14. return $achou;
  15. }else{
  16. $achou = true;
  17. return $user;
  18. }
  19. });
  20. print_r($filterUserName);

Regards

huangapple
  • 本文由 发表于 2023年6月9日 03:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定