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>";
}
OhDavey
  • 167
  • 1
  • 3
  • 9

1 Answers1

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'
    }
];
Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25