访问对象数组中最后一个对象的属性?

时间:2013-03-13 18:20:14

标签: php arrays oop

假设您有一个包含不同数量对象的数组,那么如何访问最后一个对象的属性?我尝试使用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;
        }
}

现在,我想只访问最后一个Comment项的属性,但我不确定应该怎么做?在常规数组中,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);

Format类中的方法:

// 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
}

2 个答案:

答案 0 :(得分:0)

你可以尝试:

$tempArray = array_values($data);

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

答案 1 :(得分:0)

我希望我没有错过任何重要的内容,但如果您只是想获取PHP数组的最后一个元素:

$lastItem = $data[count($data) - 1];