php - foreach - get the specific data by key name

江枫思渺然 提交于 2021-02-08 07:44:10

问题


how to get specific data by key name from the following foreach code.

    <?php
    foreach ($_SESSION as $key=>$val)
    echo $key." ".$val."<br/>";
    ?>

array is look like this want to get value of specific key.

   {"name":"bedroom","rent":"sale","props":"","leases":""}

i have tried following code but doesn't work

echo "checking key sep. ".$key[rent];

if possible i can access by key name like name or rent.


回答1:


The format is in JSON , you need to decode it first by using json_decode()

Something like this...

$yourJSON = '{"name":"bedroom","rent":"sale","props":"","leases":""}';
$yourarray = json_decode($yourJSON,1);

You can then loop the $yourarray using the foreach construct like this.

foreach($yourarray as $key=>$val)
{
echo $key." ".$val."<br/>";
}

For retrieving a specific key from it..

   echo $yourarray['rent']; //"prints" sale


来源:https://stackoverflow.com/questions/21212740/php-foreach-get-the-specific-data-by-key-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!