dongqiangse6623 2016-12-25 07:11
浏览 41
已采纳

PHP递归JSON儿童搜索

I need to parse JSON which looks like this:

{
    "mdfId":"282088127",
    "mdfConcept":"ME 3400EG-12CS-M Switch",
    "children":[
        {
            "mdfId":"007",
            "mdfConcept":"Another item",
            "children": [
                // many more here
            ]
        },
        {
             "mdfId":"008",
             "mdfConcept":"Another one",
             "children": [
                 {
                     "mdfId":"010",
                     "mdfConcept":"What I'm looking for!",
                     "children": [] // no children
                 }
             ]
        },
        // many more here
    ]
},

This is a recursive structure in which every element has mdfId, mdfConcept and children keys.

Say I need to find node with ID=010 within this structure. I don't know at which level it lies (e.g. it can be on top level, or several children nodes below).

My current approach is:

$mdfId = '010'; // what I'm loking for

foreach ($jsonResponse as $category) {
    while (true) {
        if ($category['mdfId'] == $mdfId) {
            // we found it!
            $categoryDevices[$mdfId] = $category['children'];
            break 2;
        }

        if (!empty($category['children'])) {
            next_cat:

            if (is_null($category['children'])) {
                break;
            }

            $category = array_shift($category['children']);
            continue;
        }

        if (empty($category['children'])) {
            goto next_cat;
        }
    }
}

But current approach misses some cases. How can I optimize this recursive loop so it checks all nodes on same level and each one accesible through any number of children keys?

  • 写回答

2条回答 默认 最新

  • du5407 2017-07-03 10:36
    关注

    So basically I wrote a function that didn't return anything, but rather populated a variable from arguments.

    function findRecursiveArrayNodeById($id, $array, &$node) {
        foreach ($array as $child) {
            if (isset($child['mdfId']) && $child['mdfId'] == $id) {
                $node = $child;
                return;
            }
    
            if (!empty($child['children'])) {
                findRecursiveArrayNodeById($id, $child['children'], $node);
            }
        }
    }
    

    Usage as follows:

    $result = false;
    
    findRecursiveArrayNodeById($mdfId, $category_json, $result);
    
    if (!$result) {
        println("did not find {$mdfId}");
        continue;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号