搜索关联数组以进行键/值匹配 - PHP

时间:2015-11-04 06:05:44

标签: php arrays

如何检查 $ needle 中找到的键/值对是否在关联数组 $ haystack 中,如果是,则将子数组附加到$ haystack?

正在搜索和构建的数组

$haystack = Array
    (
        [0] => Array
            (
                [animal] => 'monkey'
            )
        [1] => Array
            (
                [animal] => 'lion'
            )
        [2] => Array
            (
                [animal] => 'monkey'
            )
        )
    )

通过

循环播放数组
$needles =  = Array
    (
        [0] => Array
            (
                [animal] => 'monkey'
            )
        )
        [1] => Array
            (
                [animal] => 'ape'
            )
        )
        [3]...[99]
    )

工作选项---想要一种更有效的方法

foreach( $needles as $needle ){
    if(count($haystack)){
        $have_record = false;
        foreach( $haystack as $h ){
            if( $needle['animal'] === $h['animal'] ) {
                $have_record = true;
                break;
            }
        }
        if(!$have_record)
            array_push( $haystack, array( 'animal' => $needle['animal']) );
    } else {
      array_push( $haystack, array( 'animal' => $needle['animal']) );
    }
}

4 个答案:

答案 0 :(得分:0)

foreach($needles as $i => $needle){
    if(isset($needle['animal']) && isset($haystack[$i]['animal']) && ($needle['animal']==$haystack[$i]['animal']) ) {
        //put your required code 
    }
}

答案 1 :(得分:0)

使用此

function find_key_value($array, $key, $val)
    {
        foreach ($array as $item)
        {
           if (is_array($item))
           {
               find_key_value($item, $key, $val);
           }

            if (isset($item[$key]) && $item[$key] == $val) return true;
        }

        return false;
    }

print_r(find_key_value($array, 'animal', 'monkey'));

答案 2 :(得分:0)

尝试这个

<?php
$haystack=array(0=>array('animal'=>'monkey'),array('animal'=>'loin'),array('animal'=>'monkey'));
$needles =array(0=>array('animal'=>'monkey'));
echo $r=isMatch($haystack,$needles);

function isMatch($haystack,$needles){
$haystack_val=array_column($haystack, 'animal');
$needles_val=array_column($needles, 'animal');
$result=array_diff($haystack_val,$needles_val);
if(count($result) > 0){
    return "false";
}else
 return "true";

}

?>

答案 3 :(得分:0)

试试这个

foreach($needles as $key => $needle)
{
    if(!empty($haystack[$key]) && $haystack[$key] == $needle) 
    {
        echo "found";
    }
}