0

I am counting the amount of rows is my JSON result however I am also trying to count the number of items in the result.

The row count works but the item count won't. Getting error : Trying to get property of non-object on the $FLCount line

Code is below

// 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 Result Snippet

{
  "response": {
    "result": {
      "Accounts": {
        "row": [
          {
            "no": "1",
            "FL": [
              {
                "val": "ITEM 1",
                "content": "XX"
              },
             {
                "val": "ITEM 2",
                "content": "XX"
              },
              {
                "val": "ITEM 3",
                "content": "XX"
              }
            ]
          }
        ]
      }
    }
  }
}
Chris Yates
  • 243
  • 3
  • 16
  • 2
    `FL` is not a direct child of `row` so you need to access it by either looping `row` and accessing `FL` or hard-coding a row position `$obj->response->result->Accounts->row[0]->FL;` – MonkeyZeus Sep 26 '18 at 12:07
  • See the ***Accessing nested items*** section of [How do I extract data from JSON with PHP?](https://stackoverflow.com/a/29308899/2191572) – MonkeyZeus Sep 26 '18 at 12:11

3 Answers3

1

You have the error because $obj->response->result->Accounts->row is not an object but an array of rows.

To count all items no matter the row you can just loop through the rows and add up the number of items in each :

// 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);
}
niiwig
  • 150
  • 4
0

(EDIT: Unfortunately, I've misunderstood your requirement, and my answer addresses the solution to count it in JAVASCRIPT, instead of php)

1st problem:

One is array, another is object. In such cases, you can use:

element.length

instead of

count(element)

2nd problem:

Your actual problem is nicely expressed by user @niiwig ! However, to make it shorter, use:

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

and amount variable will have the correct number.

T.Todua
  • 53,146
  • 19
  • 236
  • 237
0
$FLCount= $obj->response->result->Accounts->row[0]->FL;

$countItems = count($FLCount);
Chayan
  • 604
  • 5
  • 12