How to Quickly Convert a PHP Object to an Associative Array
When integrating APIs that operate with object-based data, the need often arises to convert these objects to arrays to align with existing code using arrays. Here's a concise and straightforward solution to perform this conversion:
Typecast the Object:
To convert an object to an associative array, you can simply typecast it like so:
$array = (array) $yourObject;
This typecasting method is a direct and efficient approach. However, it's important to note that it only performs a shallow conversion.
Property Accessibility in Cast Arrays:
When typecasting an object to an array, various rules apply regarding property accessibility:
Integer Property Conversion:
Integer properties are inaccessible and will not appear in the converted array.
Example: Converting a Simple Object:
$object = new StdClass; $object->foo = 1; $object->bar = 2; var_dump( (array) $object );
Output:
array(2) { 'foo' => int(1) 'bar' => int(2) }
Example: Converting a Complex Object with Private and Protected Properties:
class Foo { private $foo; protected $bar; public $baz; public function __construct() { $this->foo = 1; $this->bar = 2; $this->baz = new StdClass; } } var_dump( (array) new Foo );
Output:
array(3) { 'Foofoo' => int(1) '*bar' => int(2) 'baz' => class stdClass#2 (0) {} }
As you can observe, private and protected properties are present in the converted array with the specified prepended prefixes.
Deep Casting and Non-Public Properties:
Note that this typecasting method does not perform deep casting. To access non-public attributes, you may need to explicitly apply the null bytes, as explained in the official PHP documentation.
For more in-depth information, refer to the linked resources:
The above is the detailed content of How to Quickly Convert a PHP Object into an Associative Array?. For more information, please follow other related articles on the PHP Chinese website!