【问题标题】:Finding the depth of a json in PHP在 PHP 中查找 json 的深度
【发布时间】:2012-12-21 00:01:31
【问题描述】:

在 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))
  • 有更好的方法来检查你收到了哪种 JSON 对象:第一级有一个名为“city”的键吗?如果为真,则为第二种类型,否则为第一种类型。

标签: php json


【解决方案1】:

简介

想想象你的 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2015-01-22
    • 2020-04-27
    • 1970-01-01
    • 2020-12-10
    • 2012-10-12
    相关资源
    最近更新 更多