【问题标题】:Laravel Object of class stdClass could not be converted to string. Still object when using toArray();类 stdClass 的 Laravel 对象无法转换为字符串。使用 toArray() 时仍然是对象;
【发布时间】:2020-03-11 06:00:47
【问题描述】:

我有一张表,我想通过 excel 导出。我使用toArray(); 方法,但我仍然将结果作为对象。这是我的示例代码

    $items = \DB::table('users')
            ->join('finances', 'users.id','=','finances.user_id')
            ->join('schoolyears', 'users.school_id','=','schoolyears.school_id')
            ->select('users.name','users.phone','users.section_id', 'users.student_school_id','finances.amount','finances.description','schoolyears.name as syear','finances.date')
            ->where('finances.date', '=' ,(\DB::raw("(select max(`date`) from finances f where finances.user_id=f.user_id)")))
            ->where('users.role','=','4' )
            ->where('users.school_id','=', $sid)
            ->get()->toArray();


        //    dd($items);


        } else {

            return redirect('home')->with('error', 'Invalid access');

        }

        \Excel::create($this->page_title . 's', function ($excel) use ($items) {
            $excel->sheet($this->page_title . 's', function ($sheet) use ($items) {
                $sheet->fromArray($items);
            });

dd($items)时得到的结果

array:2 [▼
  0 => {#558 ▼
    +"name": "Annamarie Morar"
    +"phone": "(0997) 212-7919"
    +"section_id": null
    +"student_school_id": "50"
    +"amount": "500"
    +"description": "New Pays"
    +"syear": "SY-2019-2020"
    +"date": "2019-11-14"
  }
  1 => {#561 ▶}
]

我想要的是这样的,以便我可以将其导出为 excel 文件

array:9 [▼
  0 => array:10 [▼
    "FirstName" => "Madelynn"
    "LastName" => "Stokes"
    "Gender" => "female"
    "Birthday" => "2013-10-09"
    "Address" => "78A/40 Goodwin Meadow, Poblacion, Iloilo City 1333 Nueva Ecija"
    "PhoneNo" => "+63 (971) 659-8143"
    "Parent" => "Deondre Stokes"
    "SchoolID" => "521"
    "RFID" => "173"
    "Section" => null
  ]
  1 => array:10 [▶]
  2 => array:10 [▶]
  3 => array:10 [▶]
  4 => array:10 [▶]
  5 => array:10 [▶]
  6 => array:10 [▶]
  7 => array:10 [▶]
  8 => array:10 [▶]
]

【问题讨论】:

  • 你可以试试这个$array = json_decode(json_encode($object), true);
  • 尝试 var_dump 而不是 dd 你得到什么结果?如果它只有dd。也 collect($items)->toArray() 应该工作
  • 感谢@DhavalPurohit。您可以发布您的答案以便我将其标记为正确吗?请向我解释您的回答以及为什么当我使用toArray(); 时结果无法转换为数组。谢谢
  • @daremachine 已经由 dhaval 回答。请向我解释我的代码有什么问题
  • 我的意思是将数组集合转换为字符串,反之亦然,这很丑陋,而且可能会占用大量内存。最好的原生解决方案是@lagbox

标签: php arrays laravel object


【解决方案1】:

您可以通过转换 Collection 将每个对象转换为数组,然后在需要时将 Collection 转换为数组:

$items = DB::table(...)->.....->get()->transform(function ($item) {
    return (array) $item;
})->toArray();

Laravel 6.x Docs - Collections - Methods - transform

【讨论】:

  • 感谢先生的回答。我会试试的。
猜你喜欢
  • 2020-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
相关资源
最近更新 更多