Home > Backend Development > PHP Tutorial > 查找数组某个指定键值,必须用遍历吗?该如何解决

查找数组某个指定键值,必须用遍历吗?该如何解决

WBOY
Release: 2016-06-13 09:58:37
Original
1175 people have browsed it

查找数组某个指定键值,必须用遍历吗?
数组格式如下:

PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->Array(    [0] => Array        (            [0] => ID            [1] => Nickname        )    [1] => Array        (            [0] => 29            [1] => Test1        )    [2] => Array        (            [0] => 654            [1] => Xxx1        ))
Copy after login

比如要找到ID=29的这条记录,我现在是使用foreach遍历数组
PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->foreach($array as $value){    if($value[0]==29)    {        //判断条件成立,进行相关操作        }}
Copy after login

请问还有没有更高效的方法?

可能有人说用in_array函数,但是假如记录中除了id为29的外,nickname这个键值也有可能会出现29的情况,用这个函数查询就会有问题。

------解决方案--------------------
$array[1]高效了
in_array不行那用array_keys($array, 29)或者array_search(29,$array)
------解决方案--------------------
PHP code
$array = array(0 => array('id', 'name'), array('29', 'test'), array('65', '29'));array_walk($array, $theValue = 'checkvalue', 29);if ($theValue == true) {    echo 'ok';}function checkvalue($value, $key, $number){    if ($value[0] == $number) {        //something        return true;    }}<div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template