我正在尝试从json src获取最小和最大温度值。我没有得到想要的结果。这就是我到目前为止所拥有的。
非常感谢您的帮助
<?php
$url = 'https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22';
$data = file_get_contents($url);
$forecasts = json_decode($data);
$length = count($forecasts->list);
for ($i = 0; $i < $length; $i++) {
$val = round($forecasts->list[$i]->main->temp, 0);
}
$min = min($val);
$max = max($val);
echo "max: ". $max ." - min: ". $max;
?>
答案 0 :(得分:5)
通过$val
循环的每一遍都将覆盖for
的值。您实际要做的是将每个值推入一个数组,然后可以取最小值和最大值:
$val = array();
for ($i = 0; $i < $length; $i++) {
$val[] = round($forecasts->list[$i]->main->temp, 0);
}
$min = min($val);
$max = max($val);
答案 1 :(得分:0)
好,所以我假设“ temp”是您要获取最小/最大的属性:
<?php
function max($list){
$highest = $list[0]->main->temp;
foreach($list as $l){
$highest = $l->main->temp > $highest ? $l->main->temp : $highest;
}
return $highest;
}
function min($list){
$lowest = $list[0]->main->temp;
foreach($list as $l){
$lowest = $l->main->temp < $lowest ? $l->main->temp : $highest;
}
return $lowest;
}
$url = 'https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22';
$data = file_get_contents($url);
$forecasts = json_decode($data);
$length = count($forecasts->list);
$min = min($forecasts->list);
$max = max($forecasts->list);
echo "max: ". $max ." - min: ". $max;
?>
应根据您的情况复制粘贴...