将 Laravel 对象转换为数组 [英] Convert laravel object to array
本文介绍了将 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?
推荐答案
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(...);
});
这篇关于将 Laravel 对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文