Usually in php, it takes some effort to process objects into arrays.
But here today, I will tell you a so easy black technique to solve this problem.
<?php /** * Created by PhpStorm. * User: zrj * Date: 17-10-20 * Time: 下午8:08 */ declare(strict_types=1);//开启强类型模式 class Person { public $name; public $age; public function __construct(string $name,int $age) { $this->name = $name; $this->age = $age; } } $jack = new Person('Jack', 18); echo print_r($jack, true); echo "<p>"; //对象转数组 $jack = json_decode(json_encode($jack), true); echo print_r($jack, true);
Let’s take a look at the results:
Person Object ( [name] => Jack [age] => 18 ) Array ( [name] => Jack [age] => 18 )
Idea analysis:
First process the object as json_encode json string.
# Perform json_decode processing on the converted json string.
json_decode(json_encode($obj),true);
##Summary:
Correct Get posture:
The object itself occupies a small amount of memory and can be used directly.
When the object itself occupies a large amount of memory (such as thousands of records forming a data set object), occupying twice the memory may cause the PHP Due to the memory limit, an exception occurred.
The above is the detailed content of Detailed explanation of the black technology of how to convert PHP objects into arrays. For more information, please follow other related articles on the PHP Chinese website!