CodeIgniter Forums
array array_sum get error message - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: General Help (https://forum.codeigniter.com/forum-24.html)
+--- Thread: array array_sum get error message (/thread-72833.html)



array array_sum get error message - DELE - 02-16-2019

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. 



RE: array array_sum get error message - jreklund - 02-16-2019

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;




RE: array array_sum get error message - DELE - 02-16-2019

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


RE: array array_sum get error message - jreklund - 02-17-2019

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); 



RE: array array_sum get error message - DELE - 02-17-2019

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.


RE: array array_sum get error message - jreklund - 02-17-2019

Not to my knowledge.