在PHP中查找json的深度
在html页面中,我可以得到下面提到的任何一个json,现在为了知道接收到了哪个json,我需要检查这些json对象的深度。有人能推荐一种在PHP中获取json对象深度的方法吗 json的两种格式如下所述:在PHP中查找json的深度,php,json,Php,Json,在html页面中,我可以得到下面提到的任何一个json,现在为了知道接收到了哪个json,我需要检查这些json对象的深度。有人能推荐一种在PHP中获取json对象深度的方法吗 json的两种格式如下所述: { "Category": { "name" : "Camera", "productDetails" : { "imageUrl" : "/assets/images/product1.png", "productName" : "GH700 D
{
"Category": {
"name" : "Camera",
"productDetails" : {
"imageUrl" : "/assets/images/product1.png",
"productName" : "GH700 Digital Camera",
"originalPrice" : 20000,
"discountPrice" : 16000,
"discount" : 20
}
}
及
导言 想想象一下你的json是这样的吗
$jsonA = '{
"Category": {
"name" : "Camera",
"productDetails" : {
"imageUrl" : "/assets/images/product1.png",
"productName" : "GH700 Digital Camera",
"originalPrice" : 20000,
"discountPrice" : 16000,
"discount" : 20
}
}';
$jsonB = '{
"city" : {
"cityname": "ABC",
"Category": {
"name" : "Camera",
"productDetails" : {
"imageUrl" : "/assets/images/product1.png",
"productName" : "GH700 Digital Camera",
"originalPrice" : 20000,
"discountPrice" : 16000,
"discount" : 20
}
}
';
问题1
现在,为了知道接收了哪个json,我需要检查这些json对象的深度。
答案1
您不需要知道哪个json
的深度,只需使用第一个键,如city
或category
范例
$json = json_decode($unknown);
if (isset($json->city)) {
// this is $jsonB
} else if (isset($json->Category)) {
// this is $jsonA
}
问题2
有人能建议一种在PHP中获取json对象深度的方法吗
echo getDepth(json_decode($jsonA, true)), PHP_EOL; // returns 2
echo getDepth(json_decode($jsonB, true)), PHP_EOL; // returns 3
使用的功能
function getDepth(array $arr) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$depth = 0;
foreach ( $it as $v ) {
$it->getDepth() > $depth and $depth = $it->getDepth();
}
return $depth;
}
count(json_decode(yourjson))有更好的方法来检查您收到的json对象的类型:第一级有一个名为“city”的键吗?如果为真,则为第二种类型,否则为第一种类型。
function getDepth(array $arr) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$depth = 0;
foreach ( $it as $v ) {
$it->getDepth() > $depth and $depth = $it->getDepth();
}
return $depth;
}