如何从结果的嵌套数组中拆分时间戳中的时间


How to split the time from a timestamp from a nested array of result?

我一直在用 php 做一个项目,我得到了一个嵌套数组,我必须从中提取值。从这个数组中,我只需要从时间戳中获取时间,即从 [ArrTime] 和 [DepTIme] 获取时间

[Segment] => stdClass Object
  (
    [WSSegment] => stdClass Object
      (
        [DepTIme] => 2014-12-10T15:40:00
        [ArrTime] => 2014-12-10T18:25:00
        [ETicketEligible] => 1
        [OperatingCarrier] => HW
      ) 
  ) 

我一直在尝试在时间戳上应用内爆功能,但它对我不起作用.

试试这个:

$DeptTime = date('H:i:s',strtotime($yourObject->Segment->WSSegment->DepTIme));
$ArrTime = date('H:i:s',strtotime($yourObject->Segment->WSSegment->ArrTime));

编写一个函数以在 php 中检索它

<?php
$str = '2014-12-10T15:40:00';
function getOnlyTime($str = '') {
  $time = '';
  if (empty($str)) {
    return $time;
  }
  return substr($str, 11);
}
echo getOnlyTime($yourObject->Segment->WSSegment->DepTIme);
echo getOnlyTime($yourObject->Segment->WSSegment->ArrTime);
?>

现场示例:

http://3v4l.org/1qChm

您可以遍历嵌套对象,并查看格式是否与日期匹配。如果是这样,请制作匹配元素的数组。您可以选择根据数组来源的索引来索引数组(如果稍后在代码中很重要;

// Starts at "Segment"
foreach ($array as $segment => $item)
{
    // Loops through the values of"WSSegment"
    foreach ($item as $part => $value)
    {
        // Checks if the value is a valid date, might need to check type; $value must be a string
        if ($date = date_create_from_format('Y-m-d'TH:i:s', $value))
        {
            // Dump to an array.
            $dates[$part][] = $date;
        }
    }
}
$dates is now an array containing all valid dates in 'DateTime format.

这是我推荐的另一种方法,原因有几个。 它使人不必使用substr()explode()手动提取数据。该代码使用两个 foreach 循环来"向下钻取到所需的项目,即出发和到达日期时间数据。如果嵌套对象的任何名称发生更改,代码仍将运行,因为它在引用这些实体时使用变量。使用 DateTime 对象的 format 属性提供了一种仅访问时间信息的便捷方法,并且可以轻松排除秒,如以下示例所示:

   <?php
   /** 
     * getTime()
     * @param $str - date/time string
     * returns time in hours and minutes
   **/
   function getTime( $str ){
       $format = "H:i"; // Hours:Minutes
       $timeObj = new DateTime( $str );
       return $timeObj->format( $format );
   }
   foreach( $obj as $nested ) {
        foreach( $nested as $n ){
            echo 'DEP - ',getTime( $n->DepTime ),"'n";
            echo 'ARV - ',getTime( $n->ArrTime ),"'n";
        }
   }

请参阅 http://3v4l.org/IdQN1