博客
关于我
laravel5.8(二十一)laravel查询结果集转为数组的方法
阅读量:391 次
发布时间:2019-03-05

本文共 1103 字,大约阅读时间需要 3 分钟。

Laravel框架从数据库中查询的结果集是以对象的 形势返回。

但是对于一些时候,使用数组,可能要比使用对象要方便一点。

这里我们大概看下,laravel中将对象结果集转换成数组的几个方法。

1:toArray()方法(只对get查询的结果集有作用)

toArray方法只对get方法查询的多条数据结果集有用。

$userInfo = DB::table("admin")                ->where("username",$username)                ->where("password",$pass)                ->get()                ->map(function ($value) {                       return (array)$value;                })->toArray();

对于first方法查询的单条结果集使用toArray会报错。

toArray只对laravel封装的框架方法有用,对执行原生sql的方法是没有用的。

如:

$userInfo = DB::select(" SELECT * FROM admin WHERE username = '{     $username}' AND password = '{     $pass}' ")->map(function ($value) {               return (array)$value;        })->toArray();

这样写是不对的。一定要注意。

2:先将对象编码成json字符串,再解码成数组

这个方法比较通用,对于get,first,以及原生sql查询的结果集都能处理。

public function objectToArray($object) {       //先编码成json字符串,再解码成数组    return json_decode(json_encode($object), true);}

3:get_object_vars()方法(只对first查询的单条结果集有作用)

DB::table('spaces')->first();//返回值是  object(stdClass)  $arrayData = get_object_vars($objectData);//返回值是array

以上大概就是将laravel查询的结果集转换为数组的三个方法。

有好的建议,请在下方输入你的评论。

欢迎访问个人博客

欢迎访问小程序:

在这里插入图片描述

转载地址:http://xohwz.baihongyu.com/

你可能感兴趣的文章
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>