php获取json数据所有的节点路径

yipeiwu_com5年前PHP代码库

之前我们讲解过使用javascript获取json数据节点路径的问题,今天我们更进一步,讲解下php获取json数据所有的节点路径

<?php

function iterTree($data) {
 $retData = array();
 $data = json_decode($data, true);
 if (!is_array($data) && empty($data)) {
 echo 'error !' ."n"; 
 } else {
 $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;
}

//测试数据
$data = file_get_contents("http://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&fiel
ds%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&fie
lds%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_des
cription&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=wx4g07
j0w1v7&is_premium=0&limit=1000&offset=24&type=geohash");

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

以上所述就是本文的全部内容了,希望大家能够喜欢。

相关文章

PHP使用CURL实现对带有验证码的网站进行模拟登录的方法

网上的很多模拟登录程序,大都是通过服务程序apache之类的运行,获取到验证码之后显示在网页上,然后填上再POST出去,这样虽然看起来很友好,但是既然模拟登录,登录后所干的事情就不一定是...

PHP中危险的file_put_contents函数详解

前言 最近在EIS上遇到一道文件上传的题,发现过滤了<,这样基本很多姿势都无效了,想了很久没做出来这题,赛后才知道是利用数组来绕过, 这里分析了下原理,话不多说了,来一起看看详细的...

PHP命令Command模式用法实例分析

本文实例讲述了PHP命令Command模式用法。分享给大家供大家参考,具体如下: 命令Command模式是GOF23种模式中的一种,是一种行为模式。这种模式很难理解。《设计模式》一书中对...

php 判断数组是几维数组

复制代码 代码如下:<?php/** * 返回数组的维度 * @param  [type] $arr [description] * @re...

php过滤所有恶意字符(批量过滤post,get敏感数据)

函数代码:复制代码 代码如下://php 批量过滤post,get敏感数据 if (get_magic_quotes_gpc()) { $_GET = stripslashes_arra...