Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-16 08:31:02
Original
822 people have browsed it

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);
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template