【问题标题】:Counting Items in JSON result计数 JSON 结果中的项目
【发布时间】:2019-03-02 04:38:21
【问题描述】:

我计算的行数是我的 JSON 结果 但是我也在尝试计算结果中的项目数。

行计数有效,但项目计数无效。 出现错误:试图在 $FLCount 行上获取非对象的属性

代码如下

// Counts The Rows - WORKS 
$row = $obj->response->result->Accounts->row;
$countRows = count($row);

// Counts The FL Items ( Doesn't Work )
$FLCount= $obj->response->result->Accounts->row->FL;
$countItems = count($FLCount);

JSON 结果片段

{
  "response": {
    "result": {
      "Accounts": {
        "row": [
          {
            "no": "1",
            "FL": [
              {
                "val": "ITEM 1",
                "content": "XX"
              },
             {
                "val": "ITEM 2",
                "content": "XX"
              },
              {
                "val": "ITEM 3",
                "content": "XX"
              }
            ]
          }
        ]
      }
    }
  }
}

【问题讨论】:

  • FL 不是row 的直接子代,因此您需要通过循环row 和访问FL 或硬编码行位置$obj->response->result->Accounts->row[0]->FL; 来访问它
  • 参见How do I extract data from JSON with PHP?访问嵌套项部分

标签: php json


【解决方案1】:

您遇到错误是因为 $obj->response->result->Accounts->row 不是一个对象,而是一个行数组。

要计算所有项目,无论是哪一行,您都可以遍历行并将每个项目的数量相加:

// Counts The Rows - WORKS 
$rows = $obj->response->result->Accounts->row;
$countRows = count($rows);

// Counts The FL Items ( Doesn't Work )
$countItems = 0;
foreach ($rows as $row) {
    $countItems += count($row->FL);
}

【讨论】:

  • 不需要遍历所有行,因为每行的项目数相同
  • 哦。然后你可以做 $couldItems = $countRows * count($obj->response->result->Accounts->row[0]->FL);
【解决方案2】:
$FLCount= $obj->response->result->Accounts->row[0]->FL;

$countItems = count($FLCount);

【讨论】:

  • 啊一直忘记 [0] 位
【解决方案3】:

(编辑:不幸的是,我误解了您的要求,我的答案解决了将其计入JAVASCRIPT,而不是php

第一个问题:

一个是array,另一个是object。在这种情况下,您可以使用:

element.length

而不是

count(element)

第二个问题:

用户@niiwig 很好地表达了您的实际问题!但是,为了使其更短,请使用:

var amount=0; JSON.parse(YOUR_RESPONSE).response.result.Accounts.row.every((obj) => amount += obj.FL.length  ); 

并且amount 变量将具有正确的数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多