将 Laravel 对象转换为数组

问题描述:

Laravel 输出:

Laravel output:

Array
(
    [0] = stdClass Object
    (
        [ID] = 5

    )

    [1] = stdClass Object
    (
        [ID] = 4

    )

)

我想把它转换成普通数组.只想删除那个 stdClass Object.我也尝试使用 ->toArray(); 但出现错误:

I want to convert this into normal array. Just want to remove that stdClass Object. I also tried using ->toArray(); but I get an error:

在非对象上调用成员函数 toArray().

Call to a member function toArray() on a non-object.

我该如何解决这个问题?

How can I fix this?

功能已在 http://www.srihost.com

UPDATE 从 Laravel 5.4 版开始就不再可能了.

您可以像@Varun 建议的那样更改您的数据库配置,或者如果您只想在这种情况下这样做,则:

You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:

DB::setFetchMode(PDO::FETCH_ASSOC);

// then
DB::table(..)->get(); // array of arrays instead of objects

// of course to revert the fetch mode you need to set it again
DB::setFetchMode(PDO::FETCH_CLASS);

对于 5.4 以上的新 Laravel (Ver > 5.4)请参阅 https://laravel.com/docs/5.4/upgrade 获取模式部分

For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(...);
});