简体   繁体   中英

Get value from json with non unique key in php

I have a json object as follows. I need to get 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.

<?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']; however this doesn't work. Would anyone know the correct way to access this?

You can get the key value using key($location) .

When key($location) returns 'non_unique_name', you can use

$location[key($location)]['val1'];

to get true (value of val1 in JSON).

use array_values to get the 'non_unique_name' key values

$array = json_decode(json_encode($json ),true);
$a =array_values($array['key']);
print_r($a[0]['val1']);

You can access the variable val1 by:

$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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM