如何将 PHP in_array 与关联数组一起使用? [英] How to use PHP in_array with associative array?

查看:29
本文介绍了如何将 PHP in_array 与关联数组一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何 php 函数,例如用于关联数组的 in_array,您可以通过 mysql 函数mysql_fetch assoc"获得?

Is there any php function such as in_array for associative arrays you get by the mysql function "mysql_fetch assoc" ?

例如,如果我有一个看起来像这样的 $array:

For example, if I have an $array that looks like this:

array(0=>(array(ID=>1, name=>"Smith"), 1=>(array(ID=>2, name=>"John"))

我可以做类似 in_array(key,value,array) 的事情吗?

或者在我的情况下,如果我正在寻找1"的 ID 值,in_array("ID",1,$array).

Or in my case, if I am looking for the ID value of "1", in_array("ID",1,$array).

这是我的解决方案,如果您认为这是正确的方法,请评论它:

This is my solution, comment on it if you think it's the right way:

function in_assoc_array($key,$value,$array)
{
    if (empty($array))
        return false;
    else
    {
        foreach($array as $a)
        {
            if ($a[$key] == $value)
                return true;
        }
        return false;
    }
}

推荐答案

试试这个.....您可以将此函数用于关联数组的任何深度.对该函数的限制是键值不会在数组中的任何位置重复.

Try this..... You can use this function for any depth of the associated array. Just contraint to this function is that the key value would not be repeat any where in array.

<?php 
function is_in_array($array, $key, $key_value){
      $within_array = 'no';
      foreach( $array as $k=>$v ){
        if( is_array($v) ){
            $within_array = is_in_array($v, $key, $key_value);
            if( $within_array == 'yes' ){
                break;
            }
        } else {
                if( $v == $key_value && $k == $key ){
                        $within_array = 'yes';
                        break;
                }
        }
      }
      return $within_array;
}
$test = array(
                0=> array('ID'=>1, 'name'=>"Smith"), 
                1=> array('ID'=>2, 'name'=>"John")
        );
print_r(is_in_array($test, 'name', 'Smith'));
?>

这篇关于如何将 PHP in_array 与关联数组一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆