Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert stdClass object to associative array in php

I need to convert this array

Array ( 
[0] => stdClass Object 
     ( [title] => primo ) 
[1] => stdClass Object 
     ( [title] => secondo )) 

to

Array ( 
[primo] => primo
[secondo] => secondo ) 

Tried different options, including typecast, still not found the correct solution

like image 841
Ponzio Pilato Avatar asked Dec 23 '15 04:12

Ponzio Pilato


People also ask

How to convert object to associative array in php?

Method 1: Using json_decode and json_encode method: The json_decode function accepts JSON encoded string and converts it into a PHP variable on the other hand json_encode returns a JSON encoded string for a given value. Syntax: $myArray = json_decode(json_encode($object), true);

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.


Video Answer


1 Answers

Use json_encode() and json_decode()

$arr = json_decode(json_encode($yourObject), TRUE);

json_decode() 's second parameter is set to TRUE.

Function definition:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth > = 512 [, int $options = 0 ]]] )

That will convert your object into an associative array.

like image 189
Pupil Avatar answered Oct 13 '22 01:10

Pupil