搜索数组 - 我在下面找到了这个函数来搜索一个对于单个字符串来说“很棒”的数组,它将匹配一个数组值和/或数组值以及数组中的匹配键,但我真正想做的是仅匹配满足/返回所有搜索值的数组。查询示例可以返回匹配任何记录的匹配 - search1或serach2 NOT匹配“search1”和“serach2”两者都匹配。
示例数组
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
所以如果你运行这些数组的函数(上面)它应该只匹配array1,因为只有array1同时搜索和键匹配。虽然array4确实匹配key1的搜索,但它不应该返回,因为它与key2的搜索不匹配,就像明智的array3一样,因为它只匹配key2。
建议&求助。
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;
该功能的“理想”格式如下:
echo recursiveArraySearch(json_decode($row['tosearch']),
array('search1'=>'key1'),array(('search2'=>'key2'));