php - 根据简码(路径)参数从对象中提取数据
问题描述
我正在为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
推荐阅读
- algorithm - 如何将内容动态定位到用户?
- python - 将字符串中的时间段转换为等效的数字天数
- python - conda 升级 python 版本并删除旧版本
- java - 查找以某个单词开头和结尾的子字符串
- protocols - 为什么数据不能写在 ASB 的基地址 +1 上
- node.js - 当在黄瓜步骤 def 中递归调用 promise 函数时,promise 返回 timdeout 5000ms
- python - 使用 Matplotlib 在 python 中设置 y 轴的顺序
- java - 让 Quarkus 健康检查在应用程序以外的另一个端口上运行
- javascript - 将箭头函数和 event.target 与事件处理程序一起使用来获取范围而不是普通函数和 this 关键字?
- python - Matlab 到 python 嵌套循环的转换