Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array into an object using stdClass() [duplicate]

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.

like image 840
Alexandrw Avatar asked Oct 09 '13 12:10

Alexandrw


1 Answers

You just add this code

$clasa = (object) 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) ); 

If you want to see is this stdClass object just call this

print_r($clasa); 

If you want to convert an array to object code will be

$arr = array('a'=>'apple','b'=>'ball'); $arr = (object) $arr; 

You don't need to use stdClass. It will automatically converted to stdClass

like image 114
Ekramul Hoque Avatar answered Oct 05 '22 10:10

Ekramul Hoque