I have an array named results_array:
var_dump($results_array):
0 => php,mysql,jquery,ruby,html,css,lamp
1 => mouse,keyboard,laptop,pad
2 => table,sofa,caption
3 => control,television,control television,television control
and I have a $q which stands for query, I want to search in the $results_array and remove the items which has nothing to do with the query, so if I set $q=a
then results array should be this:
0 => lamp
1 => keyboard,laptop,pad
3 => table,sofa,caption
4 => empty
now, I want to put the above results in each index of the results_array, at the end results_array should be:
0 => lamp
1 => keyboard
2 => laptop
3 => pad
4 => table
5 => sofa
6 => caption
my code is:
foreach ($results_array as &$row) {
$row = explode(',', $row);
}
unset($row);
$results_array = call_user_func_array('array_merge_recursive', $results_array);
foreach ($array as $k => $v) {
if (strpos($v, 'a') === false)
unset($array[$k]);
}
$results_array = array_values($results_array);
This exactly does what I need, now I set my $q = 'tele co', now after applying the above code set $ = 'tele co', it returns emtpy, but it should not because in:
3 => control,television,control television,television control
'control television,television control' should returned, but it's not, so I change my code to:
foreach ($results_array as &$row) {
$row = explode(',', $row);
}
unset($row);
$results_array = call_user_func_array('array_merge_recursive', $results_array);
// HERE IS CHANGED ****
$q = preg_split('/\s+/', trim($q));
foreach ($results_array as $key => $value) {
foreach ($q as $query) {
if (stripos($value, $query) === false) {
unset($results_array[$key]);
break;
}
}
}
// ****
$results_array = array_values($results_array);
it's still not working, by passing $q = 'tele co' I need that 'television control' and 'control television' return, because they both got 'tele' AND 'co' which is in $q.
Assuming:
$q = 'a c';
$results_array = array(
'php,mysql,jquery,ruby,html,css,lamp',
'mouse,keyboard,laptop,pad',
'table,sofa,caption',
'control,television,control television,television control'
);
Solution:
$result = array_map(function ($element) use ($q) {
$words = explode(',', $element);
return array_filter($words, function ($word) use ($q) {
$qwords = explode(' ', $q);
return count(array_filter($qwords, function ($qword) use ($word) {
return strpos($word, $qword) !== false;
})) > 0;
});
}, $results_array);
Output print_r($result);
:
Array
(
[0] => Array
(
[5] => css
[6] => lamp
)
[1] => Array
(
[1] => keyboard
[2] => laptop
[3] => pad
)
[2] => Array
(
[0] => table
[1] => sofa
[2] => caption
)
[3] => Array
(
[0] => control
[2] => control television
[3] => television control
)
)