Home  >  Article  >  Backend Development  >  How to Efficiently Convert a PHP stdClass Object to an Array?

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

DDD
DDDOriginal
2024-11-20 12:10:10214browse

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);

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));

This approach returns an indexed array without preserving property names.

Converting stdClass to Associative Array

$array = json_decode(json_encode($booking), true);

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);

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!

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