php - Cumulative sum of unique elements sorted by other element in a nested array -


i have following mysql query (timestamp in unix time, obviously):

select usr_id, concat(year(from_unixtime(timestamp)), "/", month(from_unixtime(timestamp)), "/", day(from_unixtime(timestamp))) date_stamp table order year(from_unixtime(timestamp)), month(from_unixtime(timestamp)), day(from_unixtime(timestamp)); 

this produces this:

$arr = array(     array('usr_id'=>3, 'date_stamp'=>'2011/6/6'),     array('usr_id'=>2, 'date_stamp'=>'2011/6/20'),     array('usr_id'=>2, 'date_stamp'=>'2011/6/20'), // same id , date above     array('usr_id'=>5, 'date_stamp'=>'2011/6/20'), // same date above     array('usr_id'=>1, 'date_stamp'=>'2011/6/21'),     array('usr_id'=>4, 'date_stamp'=>'2011/6/21'), // same date above     array('usr_id'=>2, 'date_stamp'=>'2011/6/21'), // same date above...         //... , same id day before ); 

i turn this:

$arr = array(     array('sum'=>1, 'date_stamp'=>'2011/6/6'),     array('sum'=>3, 'date_stamp'=>'2011/6/20'), // +2 1 of 3...         //... date duplicate     array('sum'=>5, 'date_stamp'=>'2011/6/21'), // +2 1 of 3...         //... there on different day ); 

this i've tried, later realised it's taking care of uniqueness given date, not entire array intend do:

$sum = 0; $tempres = array(); $result = array();  $date = null; foreach($arr $row) {     $date = $row['date_stamp'];     if (!in_array($row['usr_id'], $tempres))         $tempres[$date][] = $row2['usr_id']; } foreach ($tempres $date2 => $ids) {     $sum += count($ids);     $result[] = array($date2, $sum); } 

basically purpose produce cumulative sum of number of usr_id's per day , ensure same usr_id counted 1 throughout entire array, ie. make cumulative sum of unique usr_id' sorted day.

if have ideas of better optimising mysql query, welcome too.

edit: "cumulation" happen on entire array, not per day, in example output, ie. day 1 1, day 2 3 (1+2), day 3 5 (3+2)... etc.

you can first group unique users day this:

foreach ($arr $item) {     $days[$item['date_stamp']][$item['usr_id']] = 1; // value irrelevant } 

then can create array of users, union each day's users onto , count result of cumulative sum.

$all_users = array(); foreach ($days $day => $users) {     $all_users = $all_users + $users;     $result[] = array('sum' => count($all_users), 'date_stamp' => $day); } 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -