0

So I read that to convert an array to an object, I can simply use (object) in front of the variable like $my_obj = (object) $my_array. With that said, Why do I get the following error when executing the code below.

NOTICE Trying to get property of non-object on line number 26

Shouldn't I be able to access the object's properties by using $car->make?

<?php
$cars = array(
    array(
        'make' => 'Audi',
        'model' => 'A4',
        'year' => '2014',
    ),
    array(
        'make' => 'Benz',
        'model' => 'c300',
        'year' => '2015',
    ),
    array(
        'make' => 'BMW',
        'model' => 'i8',
        'year' => '2016',
    ),
);

// Convert $cars array to object
$cars = (object) $cars;

foreach ($cars as $car) {
    // Shouldn't I be able to access my object

    print $car->make . "<br>";
}
2
  • 2
    You've only cast the outer layer to an object. You probably want $car = (object) $car; inside the loop, and not outside (with $cars). Commented Jan 16, 2018 at 13:14
  • The cleanest way is indeed $object = json_decode(json_encode($array), FALSE); Commented Jan 16, 2018 at 13:30

1 Answer 1

5

You have a multidimensinal array there. By calling $cars = (object) $cars; you basically create the following object:

$cars = {
    '0' => [
        'make' => 'Audi',
        'model' => 'A4',
        'year' => '2014'
    ],
    '1' => [
        'make' => 'Benz',
        'model' => 'c300',
        'year' => '2015'
    ],
    '2' => [
        'make' => 'BMW',
        'model' => 'i8',
        'year' => '2016'
    ]
};

The inner arrays are still arrays. What you want to do isntead is transforming your inner arrays to objects, while letting your outer array be an array. This can be done with the function array_map:

$cars = array_map(function($array){
    return (object)$array;
}, $cars);

This will create your desired output.

$cars = [
    {
        'make' => 'Audi',
        'model' => 'A4',
        'year' => '2014'
    },
    {
        'make' => 'Benz',
        'model' => 'c300',
        'year' => '2015'
    },
    {
        'make' => 'BMW',
        'model' => 'i8',
        'year' => '2016'
    }
];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.