亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP 數組中不區分大小寫的搜索

PHP 數組中不區分大小寫的搜索

PHP
絕地無雙 2023-04-28 17:08:01
我想搜索 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        )
查看完整描述

1 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

這可能是您正在尋找的:


<?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);

明顯的輸出是:


Array

(

    [0] => Array

        (

            [id] => 1

            [Name] => Mobile Game

            [CategoryName] => Mobile Legend

        )

    [1] => Array

        (

            [id] => 2

            [Name] => Laptop Game

            [CategoryName] => Mobile

        )

)


查看完整回答
反對 回復 2023-04-28
  • 1 回答
  • 0 關注
  • 144 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號