-2

How can i convert an array like this to object?

Array
(
    [max] => Array
        (
            [0] => 21.
            [1] => male.
            [2] => UK.
        )

    [alex] => Array
        (
            [0] => 20.
            [1] => male.
            [2] => sweden.
        )

    [ali] => Array
        (
            [0] => 20.
            [1] => male.
            [2] => saudi arabia.
        )

)

i've alrady tried for each loop and it didn't work. is there any way to convert it ?

user229044
  • 232,980
  • 40
  • 330
  • 338
Max Zag
  • 249
  • 1
  • 2
  • 5

1 Answers1

3

Try this.

 $object =  json_decode(json_encode($array));

or you can also do this.

$object = (object) $array;

Here's a demo.

Jay Bhatt
  • 5,601
  • 5
  • 40
  • 62
  • i alrady tried it and i have an error Catchable fatal error: Object of class stdClass could not be converted to string in .... – Max Zag Jun 08 '14 at 15:04
  • @MaxZag Whats the error? – Jay Bhatt Jun 08 '14 at 15:04
  • Catchable fatal error: Object of class stdClass could not be converted to string in .... – Max Zag Jun 08 '14 at 15:05
  • 2
    @MaxZag that error is unrelated to transforming an array to object array, this error appears when your trying to echo an object array – Daryl Gill Jun 08 '14 at 15:08
  • @MaxZag like Darly Gill said the error occurs because your accessing properties of the object wrongly. Try using $object->variableName; And see the updated answer the conversion works fine. – Jay Bhatt Jun 08 '14 at 15:10