Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

search - How to use PHP in_array with associative array?

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

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

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

Can I do something like in_array(key,value,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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your case, I wonder if simply using isset() makes more sense, i.e.

isset($a[$key])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...