We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to put object to array

Hello, I have problem with objects and arrays. I want to put object values to array and them encode them to JSON, but it gives me back this:

Call to undefined method Phalcon\Mvc\Model\Resultset\Simple::setFetchMode()

Call to undefined method Phalcon\Mvc\Model\Resultset\Simple::toArray()

Call to undefined method Phalcon\Mvc\Model\Resultset\Simple::fetchArray()

What I do wrong here?

$user = $this->modelsManager->createBuilder()
                ->columns([
                    'u.name',
                ])
                ->from(['ur' => 'UserComment'])
                ->leftJoin('User', 'u.id = ur.user_id', 'u')
                ->getQuery()->execute();

        while ($row = $user->setFetchMode(\Phalcon\Db::FETCH_ASSOC)) {

           $item = array();

            $item["name"] = $row[0];

            $output[] = $item;
        }
     $out = array('aaData' => $user);
        echo json_encode($out);

OR like this:

$user = $this->modelsManager->createBuilder()
                ->columns([
                    'u.name',
                ])
                ->from(['ur' => 'UserComment'])
                ->leftJoin('User', 'u.id = ur.user_id', 'u')
                ->getQuery()->execute();

        while ($row = $user->fetchArray()) {

           $item = array();

            $item["name"] = $row[0];

            $output[] = $item;
        }
     $out = array('aaData' => $user);
        echo json_encode($out);

Maybe You could explain what I am doing wrong and how should I solve my problem?

Hi Andrew the problems is method execute() return a Simple/Complex Resultset. In your case is a Simple Resultset and I use this simple script

$users = [];
foreach ($user as $row) {
    $users[] = $row->toArray() + ['name' => 'other value'];           
}
$out = array('aaData' => $user);
echo json_encode($out);

Good luck