【问题标题】:Return results of query as array in laravel在laravel中以数组形式返回查询结果
【发布时间】:2021-03-06 01:14:37
【问题描述】:

我有这个代码

**$datas=DB::table('uni_staff')
->join('department','uni_staff.department_id','department.id')
->join('uni_staff_type','uni_staff.type_id','uni_staff_type.id')
->select('uni_staff.*','department.dep_name as departmentName' , 'uni_staff_type.user_type as 
  typeName')
->where('uni_staff.id',$id)
->select('uni_staff.*')
->get();**

我想将一行的每一列值放到一个索引数组中,或者通过列索引或其他“$datas[0]”而不是“$datas->id”等列名来打印结果

【问题讨论】:

  • 您能否详细说明预期的结果和用途是什么?
  • @MhluziBhaka 这是我的查询结果:{"id":3,"first_name":"pepe","middle_name":"ahmad","last_name":"ali","full_name ":"pep shan kj","pho_number":"ml;k","user_code":"ljl;j","type_id":1,"department_id":2,"internet1":"5654","internet2 ":"545","printer_code":546,"status":"544","date":"2020-11-18","note":"dsds","add_by":"dsd","departmentName ":"Design","typeName":"Employee"} 我想把所有的列值放到一个数组中然后使用循环打印数组

标签: php arrays database laravel


【解决方案1】:

你尝试过使用 toArray 吗?

$datas=DB::table('uni_staff')
->join('department','uni_staff.department_id','department.id')
->join('uni_staff_type','uni_staff.type_id','uni_staff_type.id')
->select('uni_staff.*','department.dep_name as departmentName' , 
'uni_staff_type.user_type as typeName')
->where('uni_staff.id',$id)
->select('uni_staff.*')
->get()
->toArray();

【讨论】:

  • 他们最终会得到一个 stdClass 对象数组
  • 错误信息:“不能使用 stdClass 类型的对象作为数组”
【解决方案2】:

无需更改任何配置,您就可以使用 Collection 将这些对象映射到数组,然后在它们上调用 array_values

$datas->map(fn ($row) => array_values((array) $row));

Laravel 8.x Docs - Collections - Available Methods - map

【讨论】:

    猜你喜欢
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2017-09-17
    • 2014-06-26
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多