laravel DB::select 结果转为数组

1、select结果

数组元素为对象,需要将对象转为数组,方便使用。

$sql = "select id, order_code, content from oms_order_log where id < 10";
$data = DB::select($sql);
dd($data);
array:10 [
  0 => {#1117
    +"id": 0
    +"order_code": "B20220409081708VHF"
    +"content": "异常校验完成"
  }
  ...
]

2、方法1:遍历

foreach ($data as &$item){
	$item = (array)$item;
}

3、方法2:使用函数

  • array_map()

    将用户自定义函数作用到数组中的每个值上,并返回用户自定义函数作用后的带有新的值的数组,类似循环遍历。

  • get_object_vars()

    返回指定 object 在当前作用域的属性组成的关联数组,即对象转数组。

$data = array_map('get_object_vars', $data);
posted @ 2022-09-23 10:43  pine007  阅读(2065)  评论(0编辑  收藏  举报