【问题标题】:PHP retrieve values recursively from JSONPHP 从 JSON 中递归检索值
【发布时间】:2014-02-22 11:45:06
【问题描述】:

我从 cURL API 获取 JSON 对象,我需要递归地遍历 JSON 并打印数组的树形视图。

下面是 JSON 对象:

{"message":"OK",
"records":{"Company INC":
    [{"positionName":"CEO",
      "seniorName":"John Doe",
      "seniorId":"1035",
      "seniorSex":"male",
      "child":[{"positionName":"Assistant to CEO",
                "seniorName":"Jane Doe",
                "seniorId":"427",
                "seniorSex":"female",
                "child":[{"positionName":"Assitant to assistant",
                          "seniorName":"James Doe",
                          "seniorId":"1370",
                          "seniorSex":"male"},
                         {"positionName":"2nd Assistant",
                          "seniorName":"Jana D. OE",
                          "seniorId":"1049",
                          "seniorSex":"female","child": ...

等等。正如你在记录部分看到的,有些人有孩子,我也需要打印出来。 这是我在对 JSON 对象进行 json_decode (true) 后使用的函数。

function recurseTree($var){
    $out = '<li>';
    foreach($var as $v){
        if(is_array($v)){
            $out .= '<ul>'.recurseTree($v).'</ul>';
        }else{
            $out .= $v." ";
        }
    }
    return $out.'</li>';
}

这很好用,除了它打印来自 JSON 的所有信息,我想在一行上只打印 SeniorName 和 positionName。

我怎样才能做到这一点?

【问题讨论】:

  • 使用json_decode 啊,在这种情况下,您(可能)已经使用is_array,您的情况与使用数组检索属性和跳过的任何其他代码有什么不同其他的?
  • 为什么不用json_decode?您必须首先将您的 json 解码为对象或数组
  • 你想输出像
  • "John Doe, CEO"
  • ...
  • "James Doe, Assitant to assistant"
  • ,对吗?
  • 我已经提到我使用json_decode之后使用该函数。 S Korolev -> 是的,这就是所需的输出
  • 标签: php json recursion


    【解决方案1】:

    使用 PHP 函数 in_array() 跳过特定的一组属性。或者用它来定义你不想跳过的键:

    $keys_to_skip = array('some', 'keys', 'to', 'skip');
    
    function recurseTree($var, $keys_to_skip){
        $out = '<li>';
        foreach($var as $k => $v){ // Note I take the key here
            if(in_array($k, $keys_to_skip)) { continue; }
    
            if(is_array($v)){
                $out .= '<ul>'.recurseTree($v, $keys_to_skip).'</ul>';
            } else {
                $out .= $v." ";
            }
        }
    
        return $out.'</li>';
    }
    

    【讨论】:

    • 根据您是否有大量的数组键,您可能需要将“$keys_to_skip”反转为“$keys_to_use”并使用 if(!in_array($k, $keys_to_use) ) { 继续; },无论哪种方式,您都需要维护一个较小的数组列表!您也可能不希望将其全部连接到一个字符串中,而是连接到一个数组中,以便您可以使用自定义排序来确保 SeniorName 位于 positionName 之前。
    • 感谢您的回答。但是,您的代码没有返回任何内容,它以某种方式跳过了所有内容,即使我在跳过数组中仅定义了 SeniorID 和 SeniorSex
    【解决方案2】:
    public static JsonNode getValuefromJsonRecursively(String jsonString, String jsonKey) {
            JsonNode result = null;
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode object = mapper.readValue(jsonString, JsonNode.class);
                result = getValuefromJsonRecursively(object, jsonKey);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;
        }
    
        public static JsonNode getValuefromJsonRecursively(JsonNode input, String jsonKey) {
    
            JsonNode result = null;
            if (input instanceof ObjectNode) {
                Iterator<String> keys = input.fieldNames();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    JsonNode value = input.get(key);
                    if (key.equals(jsonKey)) {
                        result= value;
                        break;
                    }
                    if (value instanceof ArrayNode) {
                        result= getValuefromJsonRecursively((ArrayNode) value, jsonKey);
                    }
                    else if (value.isObject()) {
                        result= getValuefromJsonRecursively((ObjectNode) value, jsonKey);
                    } 
                }
            } else if (input instanceof ArrayNode) {
                input = (ArrayNode) input;
                int arraySize = (input).size();
                for (int i = 0; i < arraySize; i++) {
                    JsonNode a = (input).get(i);
                    if (a instanceof ArrayNode) {
                        result= getValuefromJsonRecursively((ArrayNode) a, jsonKey);
                    }
                    else if (a.isObject()) {
                        result= getValuefromJsonRecursively((ObjectNode) a, jsonKey);
                    } 
                }
            }
            return result;
        }
    

    【讨论】:

    • 用户在 PHP 而不是 java 中提出了解决方案。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签