Reputation: 463
I want to search for Mobile or mobile legend or mobile. it should return both of the arrays. But my code only works if I search for the exact same word. Please help.
$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
)
Upvotes: 0
Views: 108
Reputation: 42915
This probably is what you are looking for:
<?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);
The obvious output is:
Array
(
[0] => Array
(
[id] => 1
[Name] => Mobile Game
[CategoryName] => Mobile Legend
)
[1] => Array
(
[id] => 2
[Name] => Laptop Game
[CategoryName] => Mobile
)
)
Upvotes: 1