2016-03-14 232 views
0

我有这个脚本从API获取天气数据。 但我需要每天在单独的字符串中的温度。 $ day1Max,$ day1Min,$ day2Max,$ day2Min等...从foreach循环创建多个变量

是否可以从foreach循环获取这些变量?

<?php 

$conditions_week = $forecast->getForecastWeek($latitude, $longitude); 

echo "Forecast this week:\n"; 

foreach($conditions_week as $conditions) { 
?> 

<tr> 
<th><?php  echo $conditions->getTime('Y-m-d') . ': ' . $conditions->getMaxTemperature() . "\n"; ?></th> 
<th><?php  echo $conditions->getTime('Y-m-d') . ': ' . $conditions->getMinTemperature() . "\n"; ?></th> 
</tr> 
<?php 
} 
?> 

这是输出:

enter image description here

回答

1

这里是您的解决方案:

<?php 

class Conditions{ 
    function __construct($min,$max){ 
     $this->max = $max; 
     $this->min = $min; 
    } 

    function getMaxTemperature(){ 
     return $this->max; 
    } 
    function getMinTemperature(){ 
     return $this->min; 
    } 
} 

$conditions_week = array(new Conditions(5,10),new Conditions(-5,3)); 

echo "Forecast this week:\n"; 

foreach($conditions_week as $k=>$conditions) { 
$varMin = "day".($k+1)."min"; 
$varMax = "day".($k+1)."max"; 
$$varMin = $conditions->getMinTemperature(); 
$$varMax = $conditions->getMaxTemperature(); 
?> 

<tr> 
<th><?php  echo "Max : ". $conditions->getMaxTemperature() . "\n"; ?></th> 
<th><?php  echo "Min : ". $conditions->getMinTemperature() . "\n"; ?></th> 
</tr> 
<?php 

} 


echo "day1min : " . $day1min; 
echo '<br>'; 
echo "day1max : " . $day1max; 
echo "<hr>"; 
echo "day2min : " . $day2min; 
echo '<br>'; 
echo "day2max : " . $day2max; 

你生成你的PHP变量$ day1min,$ day1max ...里面foreach,然后你可以在循环之外使用它。

下面是完整的例子:https://3v4l.org/vX5bW

+0

你,不是所有的英雄穿着斗篷的证明! 谢谢先生,这个作品完美! – Laurenz

+0

很高兴帮助你:) –