Home  >  Article  >  Backend Development  >  Detailed explanation of the black technology of how to convert PHP objects into arrays

Detailed explanation of the black technology of how to convert PHP objects into arrays

黄舟
黄舟Original
2017-10-21 11:24:031210browse

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(&#39;Jack&#39;, 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:

  1. First process the object as json_encode json string.

  2. # Perform json_decode processing on the converted json string.

    json_decode(json_encode($obj),true);

##Summary:

Advantages: Simple and fast.

Disadvantages: Will consume double times the memory.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn