组合代码以便它们相互正确连接

时间:2014-03-15 01:02:26

标签: php xml xpath foreach

我正在尝试合并

<?php
$names = $xml->xpath("/server/game/players/player[disconnect_time = '']/name");
$connect_times = $xml->xpath("/server/game/players/player[disconnect_time = '']/connect_time");
?>

<?php
foreach ($names as $name)
{
   echo $name . "<br />";
}
foreach ($connect_times as $connect_time)
{
   echo $connect_time . "<br />";
}
?>

所以他们彼此联系如下:

$ name1 - $ connect_time1
$ name2 - $ connect_time2
$ name3 - $ connect_time3

但此刻它只是按顺序回应它:

$ NAME1
$ NAME2
$ NAME3
$ connect_time1
$ connect_time2
$ connect_time3

我不太善于使用foreach - 所以我希望在这里得到一些指导。保持xpath非常重要,因为我只想显示disconnect_time为空的玩家,因为这意味着他们仍然在游戏中。 (xml存储了最近的玩家一段时间)

非常感谢你!

编辑:OH!是否可以在connect_time上添加一个小时?它应该显示的落后1小时。我有这个代码 - 但是再一次,不知道如何将它与其他代码结合起来。

$connect_time = date("Y-m-d H:i",strtotime("+1 hour",strtotime($name)));
$first  = new DateTime("now");
$second = new DateTime($connect_time);
$diff = $first->diff( $second );

编辑2:添加XML的内容以进一步帮助获得解决方案。谢谢你的帮助!

<server>
   <game>
      <players>
         <player>
            <name>Player 1</name>
            <connect_time>2014-03-15 09:05</connect_time>
            <disconnect_time/>
         </player>
         <player>
            <name>Player 2</name>
            <connect_time>2014-03-15 09:21</connect_time>
            <disconnect_time>2014-03-15 09:58</disconnect_time>
         </player>
         <player>
            <name>Player 3</name>
            <connect_time>2014-03-15 09:39</connect_time>
            <disconnect_time/>
         </player>
         <player>
            <name>Player 4</name>
            <connect_time>2014-03-15 09:50</connect_time>
            <disconnect_time>2014-03-15 10:00</disconnect_time>
         </player>
      </players>
   </game>
</server>

1 个答案:

答案 0 :(得分:0)

IMO,解决方案是选择<player> - 节点并在foreach内访问其子节点:

$players = $xml->xpath("/server/game/players/player[disconnect_time = '']");

foreach ($players as $player) {

    echo $player->name . " - " . date("Y-m-d H:i", strtotime($player->connect_time) + 3600) . PHP_EOL;

}