0

How do I get the string (3h) from this JSON object only using "rain" with php (json_decode)?

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

3 Answers 3

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

Or if you're not on PHP5.4

$keys = array_keys($struct["rain"]);
$keys[0]; // "3h";
Sign up to request clarification or add additional context in comments.

Comments

1

There are a few options for getting at the properties of that rain object, which is, in essence, what you want to do:

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

Comments

0

$arr = json_decode('{ "rain": { "3h": 3.5 } }', true);

$arr2 = $arr['rain'];

$arr3 = array_keys($arr2);

var_dump($arr3[0]); // string(2) "3h"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.