快速而肮脏的方法是使用json_encode
和json_decode
这将整个数组(包括子元素)变成一个对象。
$clasa = json_decode(json_encode($clasa)); //Turn it into an object
这同样可用于将对象转换为数组。只需添加即可返回关联的数组:, true
json_decode
$clasa = json_decode(json_encode($clasa), true); //Turn it into an array
另一种方式(不脏)只是一个递归函数:
function convertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = convertToObject($value);
}
$object->$key = $value;
}
return $object;
}
或完整代码:
<?php
function convertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = convertToObject($value);
}
$object->$key = $value;
}
return $object;
}
$clasa = array(
'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);
$obj = convertToObject($clasa);
print_r($obj);
?>
哪个输出(注意没有数组 - 只有 's):stdClass
stdClass Object
(
[e1] => stdClass Object
(
[nume] => Nitu
[prenume] => Andrei
[sex] => m
[varsta] => 23
)
[e2] => stdClass Object
(
[nume] => Nae
[prenume] => Ionel
[sex] => m
[varsta] => 27
)
[e3] => stdClass Object
(
[nume] => Noman
[prenume] => Alice
[sex] => f
[varsta] => 22
)
[e4] => stdClass Object
(
[nume] => Geangos
[prenume] => Bogdan
[sex] => m
[varsta] => 23
)
[e5] => stdClass Object
(
[nume] => Vasile
[prenume] => Mihai
[sex] => m
[varsta] => 25
)
)
因此,您可以将其引用为 .$obj->e5->nume
演示