I'm working with an API that returns a JSON object which I then decode into an array using
I need to get a count of all the [data]
items in the array, and then generate a total of all the [Total]
values contained in each
Here's my array:-
Array
(
[errorCode] => 0
[result] => OK
[data] => Array
(
[0] => Array
(
[fieldData] => Array
(
[Due Date] => 11/30/2017
[Date] => 11/30/2017
[Total] => 128.97
[Customers::Company] => A B C Lock & Key
[Status] => Paid
[Date Payment] => 11/30/2017
)
[portalData] => Array
(
)
[recordId] => 1
[modId] => 4
)
[1] => Array
(
[fieldData] => Array
(
[Due Date] => 12/01/2017
[Date] => 12/01/2017
[Total] => 256
[Customers::Company] => Kim Peacock Beringhause
[Status] => Paid
[Date Payment] => 12/01/2017
)
[portalData] => Array
(
)
[recordId] => 2
[modId] => 3
)
[2] => Array
(
[fieldData] => Array
(
[Due Date] => 11/30/2017
[Date] => 11/30/2017
[Total] => 1880
[Customers::Company] => Norton, Robert L Esq
[Status] => Unpaid Overdue
[Date Payment] =>
)
[portalData] => Array
(
)
[recordId] => 3
[modId] => 0
)
[3] => Array
(
[fieldData] => Array
(
[Due Date] => 12/22/2017
[Date] => 12/22/2017
[Total] => 1278
[Customers::Company] => Shapiro, Mark R Esq
[Status] => Unpaid
[Date Payment] =>
)
[portalData] => Array
(
)
[recordId] => 10
[modId] => 1
)
)
)
I've tried:
count($array)
which returns 3
which I can see are the count of the 3 items in that parent array (errorCode, result and data), but I can't work out how to focus on the data
only.
The count value I'm after is 4
and the total value is 3542.97
.
For count you need to do:
count($array['data']);
And for getting sum of all Total
index values:
echo array_sum(
array_column(
array_column(
$array['data'],
'fieldData'
),
'Total'
)
);
Reference:- PHP: array_column - Manual