2014-12-02 78 views
2

我一直在做一個項目在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 
    ) 

) 

我已經被嘗試應用上的時間戳的破滅功能,但它不是爲我工作。

+0

那些實際上是嵌套對象。 – 2014-12-02 07:00:45

+0

'$ dep = new DateTime($ obj-> Segment-> WSSegment-> DepTIme);' – 2014-12-02 07:07:16

回答

1

試試這個:

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

寫一個函數在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

1

你可以通過嵌套的對象循環和看看格式是否符合日期。如果是,則創建一個匹配元素的數組。你可以根據它來自何處(如果是在你的代碼事項後對指數選擇索引數組;

// 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. 
1

下面是我推薦的幾個原​​因的另一種方式它節省了一個無需手動提取使用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