0

我有一个问题,我尝试从 xml 文件中读取每天的最高温度值。我的 xml 文件如下所示:

<?xml version="1.0"?>
<temperature>
    <measure>
        <date>2013-06-19 03:18</date>
        <sensor1>25.38</sensor1>
    </measure>
    <measure>
        <date>2013-06-19 06:18</date>
        <sensor1>26.38</sensor1>
    </measure>
    <measure>
        <date>2013-06-19 09:18</date>
        <sensor1>30.31</sensor1>
    </measure>
    <measure>
        <date>2013-06-20 03:18</date>
        <sensor1>25.31</sensor1>
    </measure>
    <measure>
        <date>2013-06-20 06:18</date>
        <sensor1>23.34</sensor1>
    </measure>
    <measure>
        <date>2013-06-21 07:18</date>
        <sensor1>26.31</sensor1>
    </measure>
    <measure>
        <date>2013-06-21 10:18</date>
        <sensor1>25.31</sensor1>
    </measure>       
</temperature>

我想要的输出是这样的:

06/19 max 30.31
06/20 max 25.31
06/21 max 26.31

因为我还在学习 php,所以我卡住了。到目前为止我生成的代码是:

<?php
$xml = simplexml_load_file("test.xml");
$days = array();
$sens1Array = array();
foreach($xml as $temp){
    $days[] = $temp->date . "," . $temp->sensor1;
}
$days = array_unique($days);
foreach($days as $day){                 
    $day= explode(",", $day);
    $time = date("m/d", strtotime($day[0]));
    echo $time . " ";
    echo "max " . $day[1];
    echo "<br>";        
}   
?>

哪个输出:

06/19 max 25.38
06/19 max 26.38
06/19 max 30.31
06/20 max 25.31
06/20 max 23.34
06/21 max 26.31
06/21 max 25.31

所以我要找的是一些可以每天比较并且只输出当天最大值的代码。我已经搜索并尝试了很多,但我无法解决它。

4

1 回答 1

0

我认为下一个代码可以满足您的要求。

$xml = simplexml_load_file("test.xml");


/* aggregation of sensor maximum day values over time */

$days = array();

foreach ($xml as $measure)
{
    $time   = date("m/d", strtotime($measure->date));
    $sensor = (float) $measure->sensor1;

     if (isset($days[$time]) and $days[$time] >= $sensor) {
         continue;
     }

     $days[$time] = $sensor;         
}


/* output */

foreach ($days as $time => $sensor)
{                 
   echo $time, " max ", $sensor, "<br>\n";
}
于 2013-06-25T19:46:01.900 回答