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

我想搜索 Mobile 或 mobile legend 或 mobile。它应该返回两个数组。但是我的代码只有在我搜索完全相同的词时才有效。请帮忙。


$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

        )


绝地无双
浏览 121回答 1
1回答

潇潇雨雨

这可能是您正在寻找的:<?php$searchTerms = ['mobile', 'Mobile Legend', 'Mobile', 'mobile legend'];$data = [&nbsp; [&nbsp; &nbsp; 'id' => 1,&nbsp; &nbsp; 'Name' => "Mobile Game",&nbsp; &nbsp; 'CategoryName' => "Mobile Legend"&nbsp; ],&nbsp; [&nbsp; &nbsp; 'id' => 2,&nbsp; &nbsp; 'Name' => "Laptop Game",&nbsp; &nbsp; 'CategoryName' => "Mobile"&nbsp; ],&nbsp; [&nbsp; &nbsp; 'id' => 3,&nbsp; &nbsp; 'Name' => "Something",&nbsp; &nbsp; 'CategoryName' => "Console"&nbsp; ]];$output = [];foreach ($searchTerms as $searchTerm) {&nbsp; $pattern = sprintf('/%s/i', preg_quote($searchTerm));&nbsp; array_walk($data, function($entry, $index) use ($pattern, &$output) {&nbsp; &nbsp; if (!array_key_exists($index, $output)&nbsp; &nbsp; &nbsp; && (preg_match($pattern, $entry['Name'])&nbsp; &nbsp; &nbsp; &nbsp; || preg_match($pattern, $entry['CategoryName']))) {&nbsp; &nbsp; &nbsp; $output[$index] = $entry;&nbsp; &nbsp; }&nbsp; });}print_r($output);明显的输出是:Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [id] => 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Name] => Mobile Game&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [CategoryName] => Mobile Legend&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [id] => 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Name] => Laptop Game&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [CategoryName] => Mobile&nbsp; &nbsp; &nbsp; &nbsp; ))
打开App,查看更多内容
随时随地看视频慕课网APP