萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取 JSON 資料所有節點路徑的完整指南

前言

在處理 JSON 資料時,開發者常需要獲取所有節點的完整路徑,以便後續的資料解析或驗證。先前我們介紹過使用 JavaScript 達成此需求,今天將深入探討如何使用 PHP 實現相同功能。

核心實現:iterTree 函數

以下提供一個可直接使用的 PHP 函數 iterTree,它能夠遞迴遍歷 JSON 結構,並回傳所有節點的路徑陣列。

<?php
function iterTree($data) {
    $retData = array();
    $data = json_decode($data, true);
    
    if (!is_array($data) && empty($data)) {
        echo 'error !' . "\n";
        return $retData;
    }
    
    $queue = array();
    foreach ($data as $field => $value) {
        $queue[] = $field;
    }
    
    $head = 0;
    $tail = count($queue);
    
    while ($head < $tail) {
        $field = $queue[$head++];
        $path = explode("/", $field);
        $tmpData = &$data;
        
        foreach ($path as $key => $ph) {
            $tmpData = &$tmpData[$ph];
        }
        
        if (is_array($tmpData) && !empty($tmpData)) {
            $newField = $field;
            foreach ($tmpData as $curField => $curValue) {
                $newField = $field . '/' . $curField;
                $queue[$tail++] = $newField;
            }
        } else {
            $retData[] = $field;
        }
    }
    
    return $retData;
}

實際應用範例

以下示範如何從外部 API 獲取 JSON 資料並提取所有節點路徑:

<?php
// 測試資料:從餐廳 API 獲取 JSON
$data = file_get_contents("https://restapi.ele.me/v1/restaurants?extras%5B%5D=food_activity&extras%5B%5D=restaurant_activity&extras%5B%5D=certification&fields%5B%5D=id&fields%5B%5D=name&fields%5B%5D=phone&fields%5B%5D=promotion_info&fields%5B%5D=name_for_url&fields%5B%5D=flavors&fields%5B%5D=is_time_ensure&fields%5B%5D=is_premium&fields%5B%5D=image_path&fields%5B%5D=rating&fields%5B%5D=is_free_delivery&fields%5B%5D=minimum_order_amount&fields%5B%5D=order_lead_time&fields%5B%5D=is_support_invoice&fields%5B%5D=is_new&fields%5B%5D=is_third_party_delivery&fields%5B%5D=is_in_book_time&fields%5B%5D=rating_count&fields%5B%5D=address&fields%5B%5D=month_sales&fields%5B%5D=delivery_fee&fields%5B%5D=minimum_free_delivery_amount&fields%5B%5D=minimum_order_description&fields%5B%5D=minimum_invoice_amount&fields%5B%5D=opening_hours&fields%5B%5D=is_online_payment&fields%5B%5D=status&fields%5B%5D=supports&fields%5B%5D=in_delivery_area&geohash=wx4g07j0w1v7&is_premium=0&limit=1000&offset=24&type=geohash");

$ret = iterTree($data);
print_r($ret);

程式碼解析

  • 廣度優先搜尋(BFS):函數使用佇列機制,逐層遍歷 JSON 物件的每個鍵值對。
  • 路徑建構:透過 / 分隔符串連父子節點,形成完整路徑(如 restaurants/0/name)。
  • 引用傳遞:使用 &$tmpData 避免大量資料複製,提升效能。
  • 終止條件:當節點非陣列或為空陣列時,將該路徑加入結果集。

適用場景

  • API 回應結構分析與文件產生
  • 自動化測試中的 JSON 結構驗證
  • 資料遷移時的欄位對應檢查
  • 動態表單產生所需的欄位路徑收集

注意事項

  1. 確保 PHP 環境啟用 allow_url_fopen 以支援遠端 URL 讀取
  2. 大型 JSON 資料建議增加記憶體限制(ini_set('memory_limit', '512M');)
  3. 處理含特殊字元的鍵名時,可能需要額外的跳脫處理

這個工具函數能幫助開發者快速掌握複雜 JSON 結構的全貌,是 API 整合與資料處理中的實用利器。

copyright © 萬盛學電腦網 all rights reserved