在PHP中查找json的深度

时间:2013-01-07 09:14:49

标签: php json

在html页面中,我可以获得下面提到的任何一个jsons,现在为了知道哪个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
       }
  }
}

1 个答案:

答案 0 :(得分: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

now in order to know which json is recieved I need to check the depths of these json objects.

回答1

您不需要深度知道您需要做的json使用第一个密钥,例如citycategory

示例

$json = json_decode($unknown);
if (isset($json->city)) {
    // this is $jsonB
} else if (isset($json->Category)) {
    // this is $jsonA
}

问题2 can somebody suggest a way to get the depth of json object in PHP

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