はじめに
連想配列をオブジェクト型として扱いたいことってありませんか?
(object)
でキャストするという方法もありますが、ネストしていた場合は完全にオブジェクトとはなりません。
$array = [
'id' => 1,
'name' => 'sample',
'list' => [
'id' => 10,
'name' => 'test',
],
];
$obj = (object) $array;
echo $obj->list->name;
// PHP Notice: Trying to get property 'name' of non-object in php shell code on line 1
// Notice: Trying to get property 'name' of non-object in php shell code on line 1
var_dump($obj);
/*
object(stdClass)#3 (3) {
["id"]=>
int(1)
["name"]=>
string(6) "sample"
["list"]=>
array(2) {
["id"]=>
int(10)
["name"]=>
string(4) "test"
}
*/
結論
一旦JSON形式にしてもう一度デコードするといけるようです。
でもこのやり方は本来の用途とは違う気がするので、もしやる場合は再帰的にObjectにしたほうが良さそう。
またリソースの観点からもあまりおすすめはできないようです。
json_encodeしてjson_decodeする(非推奨)
$array = [
'id' => 1,
'name' => 'sample',
'list' => [
'id' => 10,
'name' => 'test',
],
];
$obj = json_decode(json_encode($array));
echo $obj->list->name;
// test
var_dump($obj);
/*
object(stdClass)#1 (3) {
["id"]=>
int(1)
["name"]=>
string(6) "sample"
["list"]=>
object(stdClass)#2 (2) {
["id"]=>
int(10)
["name"]=>
string(4) "test"
}
}
*/
再帰的に置換する
// ref: https://stackoverflow.com/questions/4790453/php-recursive-array-to-object
function array_to_object($array) {
$obj = new stdClass;
foreach($array as $k => $v) {
if(strlen($k)) {
if(is_array($v)) {
$obj->{$k} = array_to_object($v); //RECURSION
} else {
$obj->{$k} = $v;
}
}
}
return $obj;
}