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

1 回答 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

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;
}
于 2013-01-07T10:12:35.630 回答