您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php怎么将对象转成数组

2024/2/22 12:26:14发布13次查看
php将对象转成数组的方法:1、创建一个php示例文件;2、将对象数组使用“json_encode”函数转化为字符串;3、使用“json_decode”再转为数组即可。
本教程操作环境:windows10系统、php8.1版、dell g3电脑
说明开发过程中我们会遇到需要将实例化的对象转化为数组的情况
例如我想将处理过后的数据进行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  ]]
推荐学习:《php视频教程》
以上就是php怎么将对象转成数组的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product