Home  >  Article  >  Backend Development  >  How to Convert a stdClass Object to an Array Without Losing Rows in PHP?

How to Convert a stdClass Object to an Array Without Losing Rows in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-16 08:31:02742browse

How to Convert a stdClass Object to an Array Without Losing Rows in PHP?

How to Convert a stdClass Object to an Array in PHP

Converting an stdClass object to an array in PHP can be a tricky task, especially if the original object contains elements that are objects themselves. This question and answer provides a comprehensive solution to this problem.

The Problem

The original question describes the following issue: the user is unable to convert an stdClass object into an array without deleting the object's rows. The user has tried several methods, such as using (array) $booking, json_decode($booking, true), and a custom function, but all of these methods have resulted in an empty array.

The Solution

The solution to this problem lies in using a slightly different method: using json_encode and json_decode together to convert the object to and from JSON. This method allows for the preservation of the object's rows.

The Steps

  1. Encode the stdClass Object as JSON: Use json_encode($booking) to convert the stdClass object into a JSON string.
  2. Decode the JSON String as an Associative Array: Use json_decode(json_encode($booking), true) to convert the JSON string back into an associative array. This will convert the stdClass object into an array, while preserving the original object's rows.

The Code

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

The above is the detailed content of How to Convert a stdClass Object to an Array Without Losing Rows in PHP?. 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