首页 > 解决方案 > 根据简码(路径)参数从对象中提取数据

问题描述

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

标签: phpwordpressobject

解决方案


您可以将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

推荐阅读