I have made the following array:
$clasa = array(
'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);
I would like to know how to convert this array into an object using stdClass(), I'm a PHP beginner, a simple example would be very helpful, I've tried searching for similar questions, but the answers are complicated and go beyond my understanding of basic classes and objects.
You just add this code
If you want to see is this stdClass object just call this
If you want to convert an array to object code will be
You don't need to use stdClass. It will automatically converted to stdClass
The quick and dirty way is using
json_encode
andjson_decode
which will turn the entire array (including sub elements) into an object.The same can be used to convert an object into an array. Simply add
, true
tojson_decode
to return an associated array:An alternate way (without being dirty) is simply a recursive function:
or in full code:
which outputs (note that there's no arrays - only
stdClass
's):So you'd refer to it by
$obj->e5->nume
.DEMO
To convert array to object using stdClass just add
(object)
to array u declare.EX:
to convert object to array
to convert array to object
with these methods you can swap between array and object very easily.
Another method is to use json
But this is a much more memory intensive way to do and is not supported by versions of PHP <= 5.1
Array to stdClass can be done in php this way. (stdClass is already PHP's generic empty class)
Actually calling stdClass::__set_state() in PHP 5 will produce a fatal error. thanks @Ozzy for pointing out
This is an example of how you can use __set_state() with a stdClass object in PHP5
Or a nicer way.
or you can use this thing
use this Tutorial