How To Convert PHP Objects (Public, Private, Protected) To Assoc Array
If you have an PHP Object & want to convert it to PHP Associative Array then you can below solutions. Each one has it’s own benefit & drawbacks..
Let’s say we have this simple PHP Object coming from Json we want to convert…
$obj = json_decode( '{"name": "Saj", "from": "BD"}' );
The simplest way to do that is typecasting, although this has drawbacks which it can’t convert private or protected object except public…
$ArrayFromObj = (array) $obj;
Let’s see some examples & solutions for converting all kinds of PHP Object To Assoc Array…
- Solution 1
$object = new StdClass; $object->foo = 1; $object->bar = 2; var_dump( (array) $object );
Output:
array(2) { 'foo' => int(1) 'bar' => int(2) }
This Post Has 0 Comments