2013-01-07 66 views
3

在html頁面中,我可以得到下面提到的任何一個jsons,現在爲了知道哪個json被接收了,我需要檢查這些json對象的深度。有人可以提出一種方法來獲取PHP中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 
     } 
    } 
} 
+0

計數(json_decode(yourjson)) –

+2

有更好的方法來檢查哪種您收到JSON對象:有第一級名爲「城市」的關鍵?如果屬實,那麼它是第二種類型,否則它是第一種類型。 –

回答

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