I have an array of objects called $filtes which goes as follows:
Array
(
[0] => stdClass Object
(
[title] => Type
[alias] => type
[id] => 14
[parent_id] => 9
[subs] => Array
(
[0] => stdClass Object
(
[title] => car
[alias] => car
[id] => 15
[parent_id] => 14
)
)
)
[1] => stdClass Object
(
[title] => Model
[alias] => model
[id] => 18
[parent_id] => 9
[subs] => Array
(
[0] => stdClass Object
(
[title] => XF
[alias] => xf
[id] => 19
[parent_id] => 18
)
[1] => stdClass Object
(
[title] => XJ
[alias] => xj
[id] => 20
[parent_id] => 18
)
[2] => stdClass Object
(
[title] => XK
[alias] => xk
[id] => 21
[parent_id] => 18
)
[3] => stdClass Object
(
[title] => F-TYPE
[alias] => f-type
[id] => 22
[parent_id] => 18
)
)
)
[2] => stdClass Object
(
[title] => Condition
[alias] => condition
[id] => 24
[parent_id] => 9
[subs] => Array
(
[0] => stdClass Object
(
[title] => new
[alias] => new
[id] => 24
[parent_id] => 9
)
)
)
)
What is the best practice to check if a word exists in $filters[$i]->title and $filters[$i]->subs[$j]->title. Speed is really important in this checking.
PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
PHP in_array() Function The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
The count() function returns the number of elements in an array.
The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.
Create a simple recursive function:
function myArrayContainsWord(array $myArray, $word) {
foreach ($myArray as $element) {
if ($element->title == $word ||
(!empty($myArray['subs']) && myArrayContainsWord($myArray['subs'], $word)) {
return true;
}
}
return false;
}
Then call it like this:
if (myArrayContainsWord($filtes, $title)) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With