I have multi dimension arrays in which I want to look for some particular words this is how my array looks like
Array
(
[0] => Array
(
[sch_name] => Montfort School Roorkee
[sch_degree] => High School
[sch_field] => Commerce
[sch_grade] => A+
[sch_from_year] => 2007
[sch_to_year] => 2015
[sch_desc] => Montfort School was very nice
)
[1] => Array
(
[sch_name] => City Public
[sch_degree] => 12
[sch_field] => Commerce
[sch_grade] => 12
[sch_from_year] => 2007
[sch_to_year] => 2015
[sch_desc] => Great School
)
)
Now suppose i want to find 'montfort' word in this multi dimensional array
So i tried using this function
function searchForWord($id, $array) {
foreach ($array as $key => $val) {
if ($val['sch_name'] === $id) {
return $key;
}
}
return null;
}
echo $id = searchForWord('montfort', $p);
it resulted in nothing but when I wrote 'Montfort School Roorkee' result was found, why these word are so sensitive is there any other way to get values
Can't I use something like we do in a MySQL query LIKE '%keyword'
?
Try this:
$cols = array_column($your_array,'sch_name');
$keys = [];
foreach ($cols as $k=>$v) {
if (strpos(strtolower($cols[$k]),strtolower('Mont'))!==false) {
$keys[]=$k;
}
}
print_r($keys);
replace $your_array with your array.
it's case insensitive and will match anything partial. You could make it a function like so:
function SearchArrayForKeys($array,$column_name,$search) {
if (!$array||!is_array($array)) {
return [];
}
$cols = array_column($array,$column_name);
if (!$cols){
return [];
}
$keys = [];
foreach ($cols as $k=>$v) {
if (strpos(strtolower($cols[$k]),strtolower($search))!==false) {
$keys[]=$k;
}
}
return $keys;
}
usage:
$keys = SearchArrayForKeys($your_array,'sch_name','Mont');