将Laravel对象转换为数组 [英] Convert laravel object to array

查看:535
本文介绍了将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.

我该如何解决?

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

推荐答案

自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(Ver> 5.4)的新Laravel 参见 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆