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

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

PHPz
Release: 2020-09-04 13:58:39
Original
2427 people have browsed it

怎么从数组查找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;
    }
}
Copy after login

方法:

用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);
 
?>
Copy after login

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

Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template