我正在为Wordpress
开发自定义功能。
我有个大物件:
{
"name": "Jon",
"personal_information": {
"Age": "18",
"School": 'School_name',
},
"rewards": {
"soccer": {
"display": 'Hello soccer',
"rate": 5,
"type": 'soccer',
},
}
}
用户可以通过简码获取此信息:
[info name] // Will display "Jon"
[info rewards soccer display] // Will display "Hello soccer"
所以简码实际上是一个数组:
info = Array ()
[0] -> rewards
[1] -> soccer
[2] -> display
并从我正在做的对象中获取数据:
echo $object -> $info[0]->$info[1]->$info[2];
在循环中有没有办法做到这一点?
所以我不会有类似$info[0]->$info[1]->$info[2];
答案 0 :(得分:2)
您可以将while
循环用作:
$info = json_decode('{"name": "Jon","personal_information": {"Age": "18","School": "School_name"},"rewards": {"soccer": {"display": "Hello soccer","rate": 5,"type": "soccer"}}}');
$arr = explode(" ", "info rewards soccer display");
array_shift($arr); // remove the name of the object - info
$res = $info;
while (count($arr)) {
$key = array_shift($arr);
$res = $res->$key;
}
echo $res; // prints Hello soccer