用php获取对象JSON的名称

时间:2014-01-17 17:15:20

标签: php json

如何使用php(json_decode)中的“rain”从这个JSON对象中获取字符串(3h)?

{
    "rain": {
        "3h": 3.5
    }
}

3 个答案:

答案 0 :(得分:4)

$struct = json_decode('{
    "rain": {
        "3h": 3.5
    }
}', true); // get as associative array
array_keys($struct["rain"])[0]; // "3h"

或者如果你没有使用PHP5.4

$keys = array_keys($struct["rain"]);
$keys[0]; // "3h";

答案 1 :(得分:1)

获取雨对象的属性有几个选项,实质上就是你想要做的事情:

$json = '{
    "rain": {
        "3h": 3.5
    }
}';
$obj = json_decode($json);
$rain = $obj->rain;
$rain_properties = get_object_vars($rain);
// you now have an associative array that lists all keys and values for properties of the object
// you can look at the keys using
$rain_keys = array_keys($rain_properties);
echo $rain_keys[0]; // would give '3h' in this example
// or, you can iterate through the properties
foreach($rain_properties as $key => $value) {
    echo $key; // would give '3h' on first iteration in this example
    echo $value; // would give 3.5 in this example
}

答案 2 :(得分:0)

$ arr = json_decode('{     “下雨”:{         “3h”:3.5     } }',true);

$ arr2 = $ arr ['rain'];

$ arr3 = array_keys($ arr2);

的var_dump($ ARR3 [0]); // string(2)“3h”