2013-03-13 249 views
1

鑑於您有一個包含不同數量對象的數組,您如何訪問最後一個對象的屬性?我試圖用end($array);,但它給人的錯誤:Object of class Post could not be converted to string訪問對象數組中最後一個對象的屬性?

類是:

class Post { 
     private $datafile; 
     public $index; 
     public $subIndex; 
     public $poster; 
     public $title; 
     public $message; 
     public $date; 

// constructor and some unrelated methods here 

     public function getCommentData($givenIndex) { 
      $comments = null; 
      $data = file($this->datafile); 
      foreach($data as $row) { 
       list($index, $subIndex, $poster, $message, $date) = explode('|', $row); 
       $this->index = $subIndex; // SubIndex ties a Comment to a Post (same ID) 
       if($this->index == $givenIndex) { 
        $comment = new Post(); 
        $comment->poster = $poster; 
        $comment->message = $message; 
        $comment->date = date(DATEFORMAT, strtotime($date)); 
        $comments[] = $comment; 
       } 
      } 
      return $comments; 
     } 
} 

現在,我想只能訪問最後一個註釋項目的屬性,但我不知道應該如何做完了?在一個常規數組中,end()是快速且易於使用的,但是對於對象來說,它看起來不起作用?

下面是一個例子的var_dump:

array (size=2) 
    0 => 
    object(Post)[4] 
     private 'datafile' => null 
     public 'index' => null 
     public 'subIndex' => null 
     public 'poster' => string 'Postaaja' (length=8) 
     public 'title' => null 
     public 'message' => string 'Kommentti' (length=9) 
     public 'date' => string '5 Mar 2013 | 23:12' (length=18) 
    1 => 
    object(Post)[5] 
     private 'datafile' => null 
     public 'index' => null 
     public 'subIndex' => null 
     public 'poster' => string 'Toinenkin' (length=9) 
     public 'title' => null 
     public 'message' => string 'Lisäkommentti' (length=14) 
     public 'date' => string '5 Mar 2013 | 23:13' (length=18) 

謝謝!

編輯: 這裏是我試圖使用它的方式:

$comments = new Post(FILECOMMENTS); 
$currentComments = $comments->getCommentData($i); // $i is the index of current newspost item 

$newsComments = new Format(); 
$newsComments->formatShortComment($currentComments, $i); 

而且在格式類中的方法:

// This comment is displayed as a short text in the main News view 
public function formatShortComment($data, $index) {?> 
    <div class="newsComments"> 
     <p class="newsPreviewComment"> 
     <?php 
      $lastItem = end($data); 
      if(!empty($lastItem->message)) { 
       echo '<i>&quot;',$lastItem->message,'&quot;</i> '; 
       echo '-',$lastItem->poster; 
      } 
     ?></p> 
     &raquo; <a href="?page=comments&amp;id=<?php echo $index; ?>">Show All/Add comments</a> 
     (<?php echo $commentCount; ?>) 
    </div><?php 
} 
+1

請發佈生成錯誤的代碼。根據描述以及此處顯示的內容,它應該在理論上起作用,但如果沒有導致問題的代碼,肯定無法確定。 – Adrian 2013-03-13 18:23:11

+1

如何使用array_pop($ arrayofObjects); – Cups 2013-03-13 18:25:14

+1

@Adrian:我將代碼添加到文章 – 2013-03-13 18:32:55

回答

0

你可以嘗試:

$tempArray = array_values($data); 

$lastItem = $tempArray[count($tempArray)-1]; 
0

我希望我沒有錯過重要的東西,但是如果你只是想獲得PHP數組的最後一個元素:

$lastItem = $data[count($data) - 1]; 
相關問題