在PHP中找到JSON中的键的路径

时间:2019-04-03 17:10:04

标签: php json

我有一个由JSON表示的数据。可能看起来像这样:

$obj = {
  "lang": "en",
  "langLong": "english",
  "menu": ["Services", "About us", "Contact"],
  "pages": {
    "homepage": {
      "code": "homepage",
      "welcomeHeading": "Lorem ipsum dolor sit amet",
      "welcomeSubHeading": "Lorem ipsum dolor sit amet",
      "welcomeLink": "Lorem ipsum dolor sit amet",
      "aboutHeading": "Lorem ipsum dolor sit amet",
      "aboutSubHeading": "Ing. John Doe, FCCA",
      "aboutDescription": "Founder John Doe Lorem ipsum dolor sit amet",
      "ourServicesHeading": "Our services",
      "redBlocks": [
        {
          "heading": "Interim management",
          "items": ["first item", "second item"]
        },
        {
          "heading": "second service",
          "items": ["first item", "second item"]
        }
      ]
    },
    "services": {
      "code": "services",
      "welcomeHeading": "Interim management",
      "blocks": [
        {
          "heading": "Substitute interim management",
          "items": [
            {
              "subHeading": "target",
              "description": "
          "items": ["first item", "second item"]"
            }
          ]
        }
      ]
    }
    }
}

我正在寻找一个使用键(例如ourServicesHeading)和Object并返回搜索键路径的函数。

我试图为下面的函数编写一个函数。我面临的问题之一是对象和关联数组之间的转换。

public function findPath($obj, $key) {
            $list = array();
            if(!$obj) {
                return $list;
            }
            if(is_array($obj)) {
                foreach ($obj as $item => $value) {
                    $list = array_merge($list,[$item]);
                }
                return $list;
            }
            if(in_array($key, (array) $obj)) {
                $list = array_push($list, $obj[$key]);
            }
            if(is_object($obj) && $obj != null) {
                $children = array_keys(json_decode(json_encode($obj), true));
                $obj = json_decode(json_encode($obj), true);
                if(sizeof($children) > 0) {
                    foreach($children as $item => $value) {
                        $result = $this->findValuesHelper($obj[$children[$item]], $key);

                        $list = array_merge($list, $result);
                    }
                }
            }
            return $list;
    }

以及函数

的结果
$res = findPath($obj, "ourServicesHeading")
// "pages/homepage/ourServicesHeading"

1 个答案:

答案 0 :(得分:2)

不确定为什么需要继续转换JSON和对象中的各个部分,您可以使用一次json_decode()的第二个参数将JSON转换为基于数组的表示形式。

此代码仅将JSON转换为数组,然后调用Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Wed Apr 03 14:06:02 EDT 2019 There was an unexpected error (type=Internal Server Error, status=500). org/eclipse/jdt/internal/compiler/env/INameEnvironment 方法。我刚刚使用findPath()在此处输出结果进行测试。

我已经在代码中添加了注释,以解释主要代码...

print_r()

输出为

$json = json_decode($obj, true);

print_r(findPath($json, "ourServicesHeading"));

function findPath ( $obj, $key, $path = '' )    {
    $list = [];

    foreach ( $obj as $itemKey => $item )   {
        // Check if it's a field I'm interested in (force to string in case of a number)
        if ( (string)$itemKey == $key ) {
            // Add the matched item
            $list[] = $path."/".$itemKey;
        }
        if ( is_array($item) )  {
            // Recall this function again for next level of data, merge in the results
            $list = array_merge($list, findPath($item, $key, $path."/".$itemKey));
        }
    }

    // Pass up results
    return $list;
}

您将需要添加Array ( [0] => /pages/homepage/ourServicesHeading ) public部分,因为我已经将其编写为独立函数。