0

我有一个对象数组$comments
我通过调用TableGateway明智地调用数据库来获得它。

$comments = $this->getCommentsTable()->getComments($theme_id);

我现在需要更改数组对象元素的属性之一:

    foreach ($comments as $comment) {
        $comment->liked = 1;
    }

但是 的值$comment->liked不会改变。

我现在需要添加一个不喜欢的新属性:

    foreach ($comments as $comment) {
        $comment->disliked = 1;
    }

但它没有添加(我通过以下错误知道它):

( ! ) Notice: Undefined property: My\Model\Comments::$disliked  in C:\my\project\module\my\view\Name\operation\comment-info-panel.phtml on line 31
Call Stack
#   Time    Memory  Function    Location
1   0.0008  255368  {main}( )   ..\index.php:0
2   0.1599  6312880 Zend\Mvc\Application->run( )    ..\index.php:26
3   1.8049  9176328 Zend\Mvc\Application->completeRequest( )    ..\Application.php:322
4   1.8049  9176520 Zend\EventManager\EventManager->trigger( )  ..\Application.php:347
5   1.8050  9176648 Zend\EventManager\EventManager->triggerListeners( )

我参考了以下方法:

    foreach ($comments as &$comment) {
        $comment->disliked = 1;
    }

但我得到一个讨厌的错误:

( ! ) Fatal error: An iterator cannot be used with foreach by reference in C:\My\Project\module\Name\src\Name\Controller\MyController.php on line 804
Call Stack
#   Time    Memory  Function    Location
1   0.0010  255368  {main}( )   ..\index.php:0
2   0.1601  6312880 Zend\Mvc\Application->run( )    ..\index.php:26

感谢找到一种方法来修改和/或在此数组中的对象上添加属性。

4

1 回答 1

0

我是通过以下方式做到的:

    $commArray = array(); // Create a new array
    $count = $comments->count(); // Get the count of the resultset rows

    // Loop over the count
    for ($i = 0; $i < $count; $i++) {

        // Get the current object
        $curComm = $comments->current();

        // Here I can change easily a property of row object
        $curComm->liked = 1;

        // Here I can easily add a new property to row object
        $curComm->disliked = 1;

        // Set the cursor of the resultset to the next row object
        $comments->next();

        // Add the current row object to the array
        array_push($commArray, $curComm);
    }

    // Do whatever you like with your new array of resultset
    return $commArray;
于 2014-08-04T01:07:10.160 回答