How to convert objects into arrays with php
This article mainly introduces "how to use php to convert objects into arrays". In daily operation, I believe many people have doubts about how to use php to convert objects into arrays. Xiaobian consulted all kinds of information and sorted out simple and easy to use operation methods. I hope to answer the doubts of "how to use php to convert objects into arrays"! Next, please follow the small series to learn together!
Operating environment: Windows 7 system, PHP7.1 version, DELL G3 computer
Can php convert objects into arrays?
php converts objects to arrays
description
During development, we will encounter situations where we need to convert instantiated objects into arrays
For example, I want to export the processed data to Excel, but Excel export only
Support array format types
example
For example, the following code I need to return the value data is array type,
Although serialized as an array, but in this case returned is an array of objects
$data=$orderList->getCollection()->map(function ($order){ return new OrderResponse($order); }); dd($data->toArray());
return the following
^ 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 }]
processing method
Using json_decode() to convert strings to arrays
First, use json_encode to convert the object array to a string and then to an array.
$data=json_decode(json_encode($data),true); Returns Copyarray: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 ]] At this point, the study of "how to convert objects into arrays with php" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!