我正在为 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];
最佳答案
您可以使用 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
关于php - 根据短代码(路径)参数从对象中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55156144/