Search an array - I found this function below to search an array which is "great" for single strings, it will match an array value and or array value and matching key within an array, BUT what i really want to do is ONLY match an array where ALL the search values are met/returned. the query example could return matches for any records where there is a match for either - search1 or serach2 NOT where both "search" terms - search1 and serach2 - are met.
example arrays
array 1 - key1=>search1,key2=>search2,key3=>search3,key4=>search4
array 2 - key1=>search2,key2=>search1,key3=>search4,key4=>search2
array 3 - key1=>search3,key2=>search2,key3=>search4,key4=>search1
array 4 - key1=>search1,key2=>search3,key3=>search2,key4=>search4
so if you ran the function for these arrays (above) It should ONLY match array1 as only array1 has both search and key matched. Although array4 does match the search for key1 it should not be returned as it does not match the search for key2, like wise array3 as this only matches on key2.
Suggestions & help please.
function recursiveArraySearch($haystack, $needle, $index = null) {
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
while($it->valid()) {
if(((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
return $aIt->key();
}
$it->next();
}
return false;
}
$sql = mysql_query("SELECT * FROM atable WHERE tableID = '1' ");
while($row = mysql_fetch_array($sql)):
$content = json_decode($row['tosearch']);
echo recursiveArraySearch(json_decode($row['tosearch']), 'search1','key1');
echo recursiveArraySearch(json_decode($row['tosearch']), 'search2','key2');
endwhile;
The "ideal" format for the function would be something like this:
echo recursiveArraySearch(json_decode($row['tosearch']),
array('search1'=>'key1'),array(('search2'=>'key2'));