开发过程中我们会遇到需要将实例化的对象转化为数组的情况
例如我想将处理过后的数据进行excel导出但是excel导出只
支持数组格式类型
例子
例如下面这个代码我需要返回值data为数组类型,
虽然序列化为数组但是此时返回的是对象数组
$data=$orderList->getCollection()->map(function ($order){ return new OrderResponse($order); }); dd($data->toArray());
返回如下
^ array:8 [ 0 => app\admin\Responses\OrderResponse {#122 +"statistical_date": "2021-09-10" +"order_num": 1 +"play_type_count": 1 +"invalid_order_count": 1 } 1 => app\admin\Responses\OrderResponse {#119 +"statistical_date": "2021-09-09" +"order_num": 6 +"play_type_count": 6 +"invalid_order_count": 3 } ]
利用json_decode() 将字符串转化为数组
先将对象数组使用json_encode转化为字符串然后再转为数组即可
$data=json_decode(json_encode($data),true);
array:8 [ 0 => array:4 [ "statistical_date" => "2021-09-10" "order_num" => 1 "play_type_count" => 1 "invalid_order_count" => 1 ] 1 => array:4 [ "statistical_date" => "2021-09-09" "order_num" => 6 "play_type_count" => 6 "invalid_order_count" => 3 ] ]