Reputation: 43
I have this array with wind speeds:
Array
(
[0] => 14
[1] => 15
[2] => 16
[3] => 11
[4] => 9
[5] => 7
[6] => 8
)
When I try to calculate max and min values, instead of the expected max=16 and min=7, it returns max=11 and min=9. To make things even more difficult to understand, if the array is composed only of 2 digit wind speeds or only of 1 digit speeds, the max and min values are returned correctly, so this problem only occurs when there are 2 digit and 1 digit speed values at the same time in the array!
I tried many solutions found here like adding a leading zero, number formating, sorting the array, etc, but... no results!
The $wind_speed values are parsed from a json url like this
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-9.13,
39.4,
100
]
},
"properties": {
"meta": {
"updated_at": "2021-01-26T20:39:53Z",
"units": {
"wind_speed": "km/h"
}
},
"timeseries": [
{
"time": "2021-01-26T22:00:00Z",
"data": {
"instant": {
"details": {
"wind_speed": 16
}
}
}
},
{
"time": "2021-01-26T23:00:00Z",
"data": {
"instant": {
"details": {
"wind_speed": 9
}
}
}
},
{
"time": "2021-01-27T00:00:00Z",
"data": {
"instant": {
"details": {
"wind_speed": 7
}
}
}
}
]
}
}
From Json I get
$decoded = json_decode($rawData, true);
$timeseries=$decoded['properties']['timeseries'];
$total_events=count($timeseries);
for($k=0;$k<$total_events;$k++){
$wind_speed[$k]=$decoded['properties']['timeseries'][$k]['data']['instant']['details']['wind_speed']';
...
and then the array is created with a foreach loop,
$i = 0;
$wind= array();
foreach ($wind_speed as $windt) {
$wind[] = $windt;
if(++$i > $total_events) break;
}
....
print_r($wind); // shows expected values and is correct
echo(min($wind)); //shows correct result if array contains ONLY 2 digit or ONLY 1 digit wind speeds
echo(max($wind)); // and shows wrong result if array contains BOTH 2 digit and 1 digit wind speeds
....
Is there any reason for this to happen?
Upvotes: 0
Views: 74
Reputation: 3520
This returns the correct min/max:
<?php
$decoded = json_decode('{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-9.13,
39.4,
100
]
},
"properties": {
"meta": {
"updated_at": "2021-01-26T20:39:53Z",
"units": {
"wind_speed": "km/h"
}
},
"timeseries": [
{
"time": "2021-01-26T22:00:00Z",
"data": {
"instant": {
"details": {
"wind_speed": 16
}
}
}
},
{
"time": "2021-01-26T23:00:00Z",
"data": {
"instant": {
"details": {
"wind_speed": 9
}
}
}
},
{
"time": "2021-01-27T00:00:00Z",
"data": {
"instant": {
"details": {
"wind_speed": 7
}
}
}
}
]
}
}', true);
$wind_speed = [];
foreach ($decoded['properties']['timeseries'] as $item) {
$wind_speed[] = $item['data']['instant']['details']['wind_speed'];
}
echo "Min -> ".min($wind_speed)."\n";
echo "Max -> ".max($wind_speed)."\n";
Output is:
Min -> 7
Max -> 16
If for some reason you have a usecase that does not work, please give us the exact Json.
Upvotes: 1