2016-08-03 144 views
-1

我的數組是這樣的:如何訪問Foreach內部的對象?

Array 
(
[id] => 196011470503479_873596956078257 
[message] => #Dabur India Ltd has been ranked amongst India's Super 50 Companies by Forbes India. The annual list ranks companies that generate high returns for investors, grow their Revenues strongly and deploy funds efficiently. 
[created_time] => DateTime Object 
    (
     [date] => 2016-07-29 04:00:01.000000 
     [timezone_type] => 1 
     [timezone] => +00:00 
    ) 

[shares] => Array 
    (
     [count] => 26 
    ) 

PHP代碼

</tbody> 
    <?php 
     $i = 1; 
     foreach($arr['posts'] as $poInd=>$poVal){ 
      echo " 
       <tr> 
        <td>".$i."</td> 
        <td>".$poVal['id']."</td> 
        <td>".$poVal['name']."</td> 
        <td>".$poVal['message']."</td> 
        <td>".($poVal['created_time']->date)."</td> 
        <td>".$poVal['shares']['count']."</td> 
        <td>".count($poVal['likes'])."</td> 
        <td>".count($poVal['comments'])."</td> 
       </tr> 
      "; 
      $i++; 
     } 
    ?> 
</tbody> 

我的輸出 enter image description here 在我的表中的第5列是created_time,在我的數組created_time索引包含DateTime對象。那麼如何從foreach循環內的DateTime對象獲取日期?

回答

5

created_time是一個DateTime對象,所以你應該把它即具有使用:

$poVal['created_time']->format('Y-m-d H:i:s') 
1

您在陣列$poVal['created_time']在有日期時間對象。所以使用format與datetimeobject

$poVal['created_time']->format('Y-m-d H:i:s');

+0

這是怎麼回答'@ haz'有什麼不同? – reformed