如何在关联数组中使用PHP in_array? [英] How to use PHP in_array with associative array?

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

问题描述

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

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)?

或者在我的情况下,如果我正在寻找ID值"1",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天全站免登陆