Reputation: 1783
I have a multidimensional array like this:
$testarray = array(
array(
'First name' => 'Johnny',
'Last name' => 'Milthers',
'Age' => '24'
),
array(
'First name' => 'Toby',
'Last name' => 'Thomson',
'Age' => '25'),
),
array(
'First name' => 'Jack',
'Last name' => 'Johnson',
'Age' => '25'),
);
How do i pass search strings such as 'John', to then have the array $testarray contain only the first and last array?.
I need to pass a search term, that return the whole subarray if any of the keys values contain that string.
also if i pass "Jack Johnson", $testarray should contain only the last array.
I have been looking at a lot of stack overflow pages (and PHP manual + google), but nothing helped me out, if im posting something that already has an answer, please comment me the link.
Thank you soo much!
Upvotes: 1
Views: 93
Reputation: 64657
I haven't tested this but this should work...
function find_in_array($search, $testarray) {
$pattern = '*'.$search.'*';
$array = array_filter($testarray, function($entry) use ($pattern) {
foreach($entry as $key=>$value) {
if (fnmatch($pattern, $value)) return true;
}
return false;
});
return $array;
}
Upvotes: 1
Reputation: 10603
Here's one way of doing it, bare in mind it will only work if the search arrays are nested directly in the outer search array.
function search_array($text, $array) {
return array_filter($array, function($a) use($text){
return stristr(implode(" ", $a), $text);
});
}
http://sandbox.onlinephpfunctions.com/code/09e1187ccedba0804de5d797c350e218b05951cd
Upvotes: 3