Home >Backend Development >PHP Tutorial >怎么从数组查找key对应的值

怎么从数组查找key对应的值

PHPz
PHPzOriginal
2016-06-06 20:30:192462browse

怎么从数组查找key对应的值

从数组怎么查找key对应的值?

问题:

<br>$arr = [5=>&#39;name&#39;,8=>&#39;age&#39;,10=>&#39;city&#39;];
$num = &#39;5,10&#39;;
$str = &#39;&#39;;
//如何查找5,10对应的值,就是输出&#39;name,city&#39;,除了foreach还有什么更方便的办法?
foreach($arr as $key=>$value){
    if(strpos($num,$key) !== false) {
        $str.=$value;
    }
}

方法:

用array_key_exists判断,分解$num后通过array_key_exists在$arr数组寻找相应的值后在implode到一起。

<?php
 
$arr = array(5=-->&#39;name&#39;,8=>&#39;age&#39;,10=>&#39;city&#39;);
$num = &#39;5,10&#39;;
 
$str = array();
$explode = explode(&#39;,&#39;,$num);
foreach($explode as $key){
    if(array_key_exists($key,$arr)){
        array_push($str,$arr[$key]);
    }
}
 
echo implode(&#39;,&#39;,$str);
 
?>

更多相关技术知识,请访问PHP中文网

Statement:
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