2017-04-12 217 views
-1

如何循環訪問數組並將所有日期字段轉換爲日期對象?我有一個數組;我有數組;將日期字符串轉換爲日期時間對象

array (size=37) 
    'id' => string '12' (length=3) 
    'name' => string 'Jack' (length=6) 
    'surname' => string 'Smith' (length=1) 
    'age' => string '24' (length=1) 
    'birthdate' => string '19920512' (length=0) 
    'joindate' => string '20160923' (length=0) 
    'graduationdate' => string '' (length=0) 

我想將日期字符串轉換爲日期時間對象像這樣;

$record['birthdate'] = \DateTime::createFromFormat('Ymd', $record['birthdate']); 

但我想自動檢測日期鑰匙,使價值DateTime對象,如果該值是一個空字符串也可以只是使它假的。

我有點困惑

foreach ($record as $value) { 
    $value = \DateTime::createFromFormat('Ymd', $value['xxx']); 
} 
+0

可以循環在陣列的每一個的屬性和檢查與一個正則表達式的值。如果它匹配,(意味着它不是空的!),那麼你有一個日期字符串,你可以使用DateTime類轉換。 –

回答

1
foreach($array as $key => &$field){ 
    if(strpos($key,'date')!==false && strlen($field)==10 AND is_numeric($field)){ 
     $field = \DateTime::createFromFormat('Ymd', $field); 
    } 
} 
print_r($array); 

爲什麼這樣:

  • 我們遍歷所有key=values雙在foreach
  • 我們檢查key的字 - 部分date到檢測到的日期字段
  • 然後我們檢查是否有可用的數字與10位
  • 如果一切正常,我們做一個對象從價值
  • 而且由於在foreach使用&,我們在數組中直接更改值。

有愉快的一天

+0

儘管此代碼片段可能會解決問題,但[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-基於代碼的答案)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –

+0

@JohnConde確定,添加了一些信息。 – JustOnUnderMillions

+0

很好的回答。我已經有該循環將數字字符串轉換爲整數和浮點數,並將空字符串轉換爲空值,我可以添加如果日期部分。我從來沒有想過'strpos' – Mentos93

-1

您可以使用strtotime()http://uk.php.net/manual/en/function.strtotime.php包含日期字符串轉換。

<?php 
// both lines output 813470400 
echo strtotime("19951012"), "\n", 
    strtotime("12 October 1995"); 
?> 

可以傳遞的結果作爲第二個參數,以日期()將自己重新格式化日期:

<?php 
// prints 1995 Oct 12 
echo date("Y M d", strtotime("19951012")); 
?> 
+0

我的回答錯了嗎?爲什麼投下這個? – user3441151

相關問題