CodeIgniter Forums

Full Version: Need Idea foreach
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi CI Team,
How to foreach data like below,

Database :
Code:
ID | viewed | code
1 | 15 | US
2 | 20 | SG
3 | 10 | US
4 | 30 | SG
5 | 30 | SG
6 | 55 | MY

How to get output like below,
Code:
var gdpData = {"US": 25,

"SG": 80,

"MY": 55,
};

Thanks  Huh
where your getting data from?
if this data in database you can use group by and sum sql functions to get

viewed | code
25        | US
85        | SG
55         | MY

or if discribe it in php array: 
PHP Code:
array(
 
 array('viewed' => 25'code' => 'US'),
 
 array('viewed' => 85'code' => 'SG'),
 
 array('viewed' => 55'code' => 'MY')




your gdpData is in json format. you will need to map to 


PHP Code:
array(
 
   'US' => 25,
 
   'SG' => 85,
 
   'MY' => 55

 this format and then use json_encode PHP function. it will give following result:

{"US":25,"SG":85,"MY":55}

Also to parse json you can use json_decode function in PHP
(04-25-2018, 11:05 PM)neuron Wrote: [ -> ]where your getting data from?
if this data in database you can use group by and sum sql functions to get

viewed | code
25        | US
85        | SG
55         | MY

or if discribe it in php array: 
PHP Code:
array(
 
 array('viewed' => 25'code' => 'US'),
 
 array('viewed' => 85'code' => 'SG'),
 
 array('viewed' => 55'code' => 'MY')




your gdpData is in json format. you will need to map to 


PHP Code:
array(
 
   'US' => 25,
 
   'SG' => 85,
 
   'MY' => 55

 this format and then use json_encode PHP function. it will give following result:

{"US":25,"SG":85,"MY":55}

Also to parse json you can use json_decode function in PHP


I try use this code,
PHP Code:
$rv = array();
 
       foreach($views_data as $v) {
 
           $rv = array(
 
               $v['country_code'] => $v['viewed'],
 
           );
 
       }
 
           
        $result 
json_encode($rv,true); 

The result is OK, but how to sum the viewed ?

Thanks you neuron...
You need to sum the result in SQL query, not in foreach.