How to Efficiently Convert a PHP stdClass Object to an Array?

DDD
Release: 2024-11-20 12:10:10
Original
213 people have browsed it

How to Efficiently Convert a PHP stdClass Object to an Array?

Converting an stdClass to Array in PHP

Question:

I need to convert a PHP stdClass object into an array. However, attempts using (array) casting, json_decode(true), and json_decode() have resulted in an empty array. How can I perform this conversion effectively?

Answer:

Lazy One-Liner Method

For a slightly compromised performance, you can leverage the JSON methods to achieve this conversion in a concise manner:

$array = json_decode(json_encode($booking), true);
Copy after login
Copy after login

This method first encodes the object into a JSON string and then decodes it back into an array.

Converting stdClass to Array

$array = (array) json_decode(json_encode($booking));
Copy after login

This approach returns an indexed array without preserving property names.

Converting stdClass to Associative Array

$array = json_decode(json_encode($booking), true);
Copy after login
Copy after login

By passing true as the second argument to json_decode, you can convert the object into an associative array, preserving property names.

Custom Function (Recursive)

If performance is critical, you can implement a custom recursive function to convert the object to an array:

function object_to_array($object) {
  if (is_object($object)) {
    $object = get_object_vars($object);
  }

  if (is_array($object)) {
    return array_map(__FUNCTION__, $object);
  } else {
    return $object;
  }
}

$array = object_to_array($booking);
Copy after login

The above is the detailed content of How to Efficiently Convert a PHP stdClass Object to an Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template