繁体   English   中英

PHP 数组中不区分大小写的搜索

[英]Case insensitive search in PHP array

我想搜索移动或移动图例或移动。 它应该返回两个 arrays。 但是我的代码只有在我搜索完全相同的单词时才有效。 请帮忙。

$resutls = [];
$words = ['mobile', 'Mobile Legend', 'Mobile', 'mobile legend']; 

foreach ($items as $item) {
   if(in_array($item['CategoryName'], $words)) {
      $results[] = $item;
   }
}
print_r($results);

[0] => Array
        (
            [id] => 1
            [Name] => Mobile Game,
            [CategoryName] => Mobile Legend
        )
     [1] => Array
        (
            [id] => 2
            [Name] => Laptop Game
            [CategoryName] => Mobile
        )

这可能是您正在寻找的:

<?php
$searchTerms = ['mobile', 'Mobile Legend', 'Mobile', 'mobile legend'];
$data = [
  [
    'id' => 1,
    'Name' => "Mobile Game",
    'CategoryName' => "Mobile Legend"
  ],
  [
    'id' => 2,
    'Name' => "Laptop Game",
    'CategoryName' => "Mobile"
  ],
  [
    'id' => 3,
    'Name' => "Something",
    'CategoryName' => "Console"
  ]
];
$output = [];
foreach ($searchTerms as $searchTerm) {

  $pattern = sprintf('/%s/i', preg_quote($searchTerm));

  array_walk($data, function($entry, $index) use ($pattern, &$output) {
    if (!array_key_exists($index, $output)
      && (preg_match($pattern, $entry['Name'])
        || preg_match($pattern, $entry['CategoryName']))) {
      $output[$index] = $entry;
    }
  });

}

print_r($output);

明显的 output 是:

Array
(
    [0] => Array
        (
            [id] => 1
            [Name] => Mobile Game
            [CategoryName] => Mobile Legend
        )
    [1] => Array
        (
            [id] => 2
            [Name] => Laptop Game
            [CategoryName] => Mobile
        )
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM