php - 根据短代码(路径)参数从对象中提取数据

标签 php wordpress object

我正在为 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/

相关文章:

php - 将MySQL数据合并到同一个列表中

php - 使用 HTML FORM 和 PHP 使用 POST 方法将数据添加到 MYSQL

php - WordPress - 覆盖短代码

wordpress - 主目录中的 Htaccess 与子目录冲突

javascript - 计算对象内部对象内部的值

javascript - 有没有办法以对象格式查看/记录 JavaScript 函数?

java - PHP - 如何检查两个引用是否指向同一底层对象(内存地址)?

php - 不使用 htmlentities 编码已经编码的项目

mysql - 多列索引需要添加主键吗?

Java 对象引用机制