[英]Get value from json with non unique key in php
I have a json object as follows. 我有一个JSON对象,如下所示。 I need to get
val1
. 我需要得到
val1
。 I can do this using the following code if I specify the non_unique_name
however as the name implied this can change so I am unable to retrieve it. 如果我指定了
non_unique_name
我可以使用以下代码来执行此操作,但是由于名称所隐含的名称可能会更改,因此无法检索它。
<?php
$json = '{"key": {"non_unique_name": {"val1": true, "val2": flase}}}';
$array = json_decode( $json, true );
print_r( $array );
$location = $array['key'];
echo $location['non_unique_name']['val1'];
?>
I have tried to access it using echo $location[0]['val1'];
我试图使用
echo $location[0]['val1'];
访问它echo $location[0]['val1'];
however this doesn't work. 但是,这不起作用。 Would anyone know the correct way to access this?
有人知道访问此内容的正确方法吗?
You can get the key value using key($location)
. 您可以使用
key($location)
获得键值。
When key($location)
returns 'non_unique_name', you can use 当
key($location)
返回'non_unique_name'时,您可以使用
$location[key($location)]['val1'];
to get true
(value of val1 in JSON). 以获得
true
(JSON中val1的值)。
use array_values
to get the 'non_unique_name'
key values 使用
array_values
获取'non_unique_name'
键值
$array = json_decode(json_encode($json ),true);
$a =array_values($array['key']);
print_r($a[0]['val1']);
You can access the variable val1
by: 您可以通过以下方式访问变量
val1
:
$json = '{"key": {"non_unique_name": {"val1": true, "val2": false}}}';
$json_array = json_decode($json);
foreach($json_array as $val)
{
echo $val->non_unique_name->val1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.