我有一个风速数组:
Array
(
[0] => 14
[1] => 15
[2] => 16
[3] => 11
[4] => 9
[5] => 7
[6] => 8
)
当我尝试计算最大和最小值时,而不是预期的max=16和min=7,它返回max=11和min=9。为了让事情变得更加难以理解,如果数组仅由2位数的风速或1位数的速度组成,则最大值和最小值将正确返回,因此只有当数组中同时存在2位数和1位数的速度值时才会出现此问题!
我在这里尝试了许多解决方案,如添加前导零,数字格式化,排序数组等,但是…没有结果!
$wind_speed值是从json url解析的,如下所示
{
"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
}
}
}
}
]
}
}
从Json中得到
$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']';
...
,然后用foreach循环创建数组,
$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
....
发生这种情况有什么原因吗?
返回正确的最小/最大值:
<?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";
输出是:
Min -> 7
Max -> 16
如果由于某种原因你有一个不能工作的用例,请给我们准确的Json。