xendras
xendras

Reputation: 31

Finding the depth of a json in PHP

In the html page I can get any one of the below mentioned jsons, now in order to know which json is recieved I need to check the depths of these json objects. can somebody suggest a way to get the depth of json object in PHP.

The two formats of the json are mentioned below:

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

and

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

Upvotes: 3

Views: 1652

Answers (1)

Baba
Baba

Reputation: 95101

Introduction

Want to imagine your json looks like this

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

Question 1

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

Answer 1

You do not need the depth to know which json it all you need to do is use the first key such as city or category

Example

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

Question 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 Used

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

Upvotes: 3

Related Questions