How Can I Convert PHP Objects into Arrays?
Dec 12, 2024 am 11:15 AMConverting Objects to Arrays
Objects in PHP can be converted into arrays to facilitate easier manipulation and data retrieval. Here are three methods to achieve this conversion:
Single-Dimensional Arrays
- Array Casting: Using (array) will cast an object into an array, including all public, private, and protected members.
$array = (array) $object;
- get_object_vars Function: This function returns an array containing only the publicly accessible properties of an object unless called from within the object's scope.
$array = get_object_vars($object);
Multi-Dimensional Arrays
To convert multi-dimensional objects, the following approaches can be used:
- JSON Encoding and Decoding: By encoding the object to JSON and then decoding it back as an array, you can obtain a multi-dimensional array. Note that this method excludes private and protected members and is not suitable for objects containing non-JSON-encodable data.
$array = json_decode(json_encode($object), true);
- ObjectToArray Function: This custom function recursively converts an object to an array, including private and protected members.
function objectToArray($object) { if (!is_object($object) && !is_array($object)) return $object; return array_map('objectToArray', (array) $object); }
By utilizing these methods, you can effectively convert PHP objects into arrays for various use cases, enabling seamless data manipulation and retrieval.
The above is the detailed content of How Can I Convert PHP Objects into Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
