php - foreach - 通过键名获取具体数据

2021-12-26 00:00:00 arrays foreach php

如何从以下 foreach 代码中通过键名获取特定数据.

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.

推荐答案

格式为JSON,需要先使用json_decode()

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

这样的东西...

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

然后您可以像这样使用 foreach 构造来循环 $yourarray.

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

相关文章