• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
array array_sum get error message

#1
Results from the table:
Code:
Array (
   [0] => stdClass Object (
       [ID] => 00058
       [income_campaign] => 00001
       [income_country] =>
       [income_value] => 0.00
       [income_date] => 2019-02-11
       )
   [1] => stdClass Object (
       [ID] => 00056
       [income_campaign] => 00001
       [income_country] => 1US, 3PH, 2CN, 9TH
       [income_value] => 12.00
       [income_date] => 2019-02-12
   )
   [2] => stdClass Object (
       [ID] => 00059
       [income_campaign] => 00001
       [income_country] => 1US
       [income_value] => 12.00
       [income_date] => 2019-02-10
   )
   [3] => stdClass Object (
       [ID] => 00061
       [income_campaign] => 00001
       [income_country] => 2US
       [income_value] => 12.00
       [income_date] => 2019-02-09
   )
)

I want to sum an income_value value, so the results obtained are 36.00

I have tried this code but always get an error message:

PHP Code:
$sum = array();

foreach (
$data['data_user_income'] as $a => $b) {

   foreach (
$b as $c => $d) {
      
$sum[$c]+=$d;
   }
}
print_r($sum);

// Error message :
// Message: Undefined index: ID,income_value .... etc. 
Reply

#2
Those aren't arrays, but objects inside an array.
So that would be:

PHP Code:
$sum 0;
foreach(
$data['data_user_income'] as $d) {
 
  $sum += $d->income_value;

Reply

#3
thank you very much for your help, but why are the results not decimal if using this method?
Reply

#4
As there are no decimals to be added, it removes it.
If you wan't to display them with decimals, you need to use number_format.

http://php.net/manual/en/function.number-format.php
PHP Code:
echo number_format($sum2); 
Reply

#5
But is there really no other way to add these decimal values? because I save a decimal value in the database.

I agree with what you explained above, but I prefer simpler code if there is one.
Reply

#6
Not to my knowledge.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.