问题描述
所以我读到了将数组转换为对象的方法,我可以简单地在变量前使用(object)
,例如 $ my_obj = (对象)$ my_array
。话虽如此,为什么执行下面的代码时为什么出现以下错误。
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.
我不能使用 $ car-> make
访问对象的属性吗?
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>";
}
推荐答案
您在那里有一个多维数组。通过调用 $ cars =(对象)$ cars;
,您基本上创建了以下对象:
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'
]
};
内部数组仍然是数组。您想要做的是将内部数组转换为对象,同时让外部数组成为数组。可以使用函数 array_map
:
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);
这将创建所需的输出。
$cars = [
{
'make' => 'Audi',
'model' => 'A4',
'year' => '2014'
},
{
'make' => 'Benz',
'model' => 'c300',
'year' => '2015'
},
{
'make' => 'BMW',
'model' => 'i8',
'year' => '2016'
}
];
这篇关于在PHP中将数组转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!