Skip to content
Advertisement

PHP – Grab info from array

Im trying to get sensor value from my weather station. The API i get is in the array.

I can’t figure out how to only grab “temp” data from [“id”]=> “1549112871”. If I echo $sensor[“temp”] I will get temp data from whole array.

// Send the request & save response to $resp
$resp = curl_exec($ch);
$jsonResp = json_decode($resp, true);

$eachSensor = $jsonResp["sensor"];
// Close request
curl_close($ch);

foreach ($eachSensor as $sensor) {
?>

<h2><?php if(!empty($sensor["rrate"])) { echo $sensor["rrate"] . " mm nederbörd senaste 
dygnet"; } else { /* */ }?></h2>

<?php } ?>

<h3><?php echo "Det blåser för tillfället " . $sensor["wgust"] . " m/s";?></h3>

array(16) { ["id"]=> string(10) "1547443848" ["name"]=> string(9) "Friggebod" 
["lastUpdated"]=> int(1640767771) ["ignored"]=> int(0) ["client"]=> string(6) "592885" 
["clientName"]=> string(3) "Hem" ["online"]=> string(1) "1" ["editable"]=> int(1) 
["battery"]=> int(254) ["keepHistory"]=> int(1) ["protocol"]=> string(10) "fineoffset" 
["model"]=> string(19) "temperaturehumidity" ["sensorId"]=> string(2) "15" ["miscValues"]=> 
string(13) "{"chId": 151}" ["temp"]=> string(3) "3.4" ["humidity"]=> string(2) "62" }

array(16) { ["id"]=> string(10) "1549112896" ["name"]=> string(10) "Regnsensor" 
["lastUpdated"]=> int(1640767565) ["ignored"]=> int(0) ["client"]=> string(6) "592885" 
["clientName"]=> string(3) "Hem" ["online"]=> string(1) "1" ["editable"]=> int(1) 
["battery"]=> int(253) ["keepHistory"]=> int(1) ["protocol"]=> string(6) "oregon" ["model"]=> 
string(4) "2914" ["sensorId"]=> string(2) "31" ["miscValues"]=> string(12) "{"chId": 19}" 
["rrate"]=> string(1) "0" ["rtot"]=> string(4) "49.5" } 

array(16) { ["id"]=> string(10) "1549112871" ["name"]=> string(7) "Ute Tak" ["lastUpdated"]=> 
int(1640767645) ["ignored"]=> int(0) ["client"]=> string(6) "592885" ["clientName"]=> 
string(3) "Hem" ["online"]=> string(1) "1" ["editable"]=> int(1) ["battery"]=> int(254) 
["keepHistory"]=> int(1) ["protocol"]=> string(6) "oregon" ["model"]=> string(4) "F824" 
["sensorId"]=> string(2) "29" ["miscValues"]=> string(12) "{"chId": 19}" ["temp"]=> string(4) 
"-0.1" ["humidity"]=> string(2) "97" } 

Advertisement

Answer

As your provided data, your data is a 2-dimensions array. Each array will have the keys: “id”, “temp”,… And you want to get the “temp” value of the array that has a specific “id”.

If you want to do so, you must loop through the array to find which array matched the desired “id”:

foreach ($eachSensor as $sensor) {
    if ($sensor['id'] != '1549112871') {
        continue;
    }

    // Your code here...
    // This $sensor has the id value equal to 1549112871
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement