在PHP中查找JSON的深度

3

在html页面中,我可以获取以下任意一个json对象。为了知道接收到的是哪个json对象,我需要检查这些json对象的深度。有人能建议一种在PHP中获取json对象深度的方法吗?

下面列出了两种json格式:

{
  "Category": {
    "name" : "Camera",
    "productDetails" : {
      "imageUrl" : "/assets/images/product1.png",
      "productName" : "GH700 Digital Camera",
      "originalPrice" : 20000,
      "discountPrice" : 16000,
      "discount" : 20
     }
}

并且

{
  "city" : {
    "cityname": "ABC",
    "Category": {
      "name" : "Camera",
      "productDetails" : {
        "imageUrl" : "/assets/images/product1.png",
        "productName" : "GH700 Digital Camera",
        "originalPrice" : 20000,
        "discountPrice" : 16000,
        "discount" : 20
       }
  }
}

count(json_decode(yourjson)) - Arun Killu
2
有更好的方法来检查你收到了哪种JSON对象:第一层是否有一个名为“city”的键?如果是,则是第二种类型,否则是第一种类型。 - STT LCU
1个回答

3

介绍

如果想象你的 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,你只需要使用第一个键,比如citycategory即可。

例如:

$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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接