calculate total minutes of it's own ID in db table - php

I am trying to show some stats given date ranges. In table rows there are many ID's and trying to calculate total minutes of it's own ID.
Currently returns values as below:
{"id":"25","minute":13}
{"id":"17","minute":12}
{"id":"16","minute":10}
{"id":"17","minute":10}
{"id":"16","minute":4}
{"id":"34","minute":5}
{"id":"17","minute":21}
{"id":"30","minute":12}
{"id":"30","minute":13}
{"id":"30","minute":50}
Controller
public function actionStats() {
if (isset($_POST['begin'], $_POST['end'])) {
$begin = strtotime($_POST['begin']);
$end = strtotime($_POST['end']);
$Criteria = new CDbCriteria();
$Criteria->condition = "created >= $begin and created <= $end and status=1";
$transcripts = Transcripts::model()->findAll($Criteria);
foreach($transcripts as $transcript) {
$op = $transcript->opID;
$minute = $transcript->ended - $transcript->created;
echo json_encode(array("id" => $op, "minute" => floor($minute/60)));
}
}
}

I'd modify your code to look like:
public function actionStats()
{
if (isset($_POST['begin'], $_POST['end']))
{
$begin = strtotime($_POST['begin']);
$end = strtotime($_POST['end']);
$Criteria = new CDbCriteria();
$Criteria->condition = "created >= $begin and created <= $end and status=1";
$transcripts = Transcripts::model()->findAll($Criteria);
$transcriptTotals = array();
foreach($transcripts as $transcript)
{
$op = $transcript->opID;
$minute = $transcript->ended - $transcript->created;
if (array_key_exists($op, $transcriptTotals)) {
$transcriptTotals[$op] += floor($minute/60);
} else {
$transcriptTotals[$op] = floor($minute/60);
}
}
echo json_encode($transcriptTotals);
}
}
This should result in output that looks like:
{'1':'2', 'id':'sumOfMinutes', etc}
If your JSON needs to be like you specified above, you would have code like:
foreach ($transcriptTotals as $id=>$sum) {
echo json_encode(array('id'=>$id, 'minutes'=>$sum));
}

How about adding it up in the MySQL query already? E.g. with the SUM function:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

Related

How to retrieve all media entries in Kaltura, beyond the 10k mark?

I am using the php5.3 SDK: https://github.com/kaltura/KalturaGeneratedAPIClientsPHP53
We have 90k media entries, but I can only got 20k entries. The following code is straight forward. Could anyone help me out?
// Main entry point
public function mywrite(Route $route, Console $console)
{
// Max records is 500, the range cannot be too big.
$range = 3600 * 24;
$this->__mywrite($route, $console, $range);
}
// Count how many objects we can get
// $veryStartDate == 1446173087, sep 2015
// $maxDate == 1526469375, may 2018
public function __mywrite($route, $console, $range) {
$configObj = $this->readMyWriteHistoryConfigFile();
$lastProcessObj = $this->readMyWriteLastProcessFile();
//
$veryStartDate = $configObj->veryStartDate;
$maxDate = $configObj->maxDate;
// Set start Date
$startDate = $veryStartDate;
$endDate = $startDate + $range;
//
$totalCount = 0;
while($startDate <= $maxDate) {
$objs = $this->listMediaByLastPlay($startDate, $endDate);
$totalCount += count($objs);
echo "\n$startDate - $endDate:\n";
echo "\n". count($objs). "\n";
$startDate = $endDate + 1;
$endDate = $endDate + $range;
} // end while loop
// we get like 25k records, but we have 90k records....
echo "\ncount: $totalCount\n";
}
// we call the client and get records by start last play date and end last play date
public function listMediaByLastPlay($startDate, $endDate) {
// Page size
$pageSize = 1000;
// Client with admin
$client = $this->getClient(\KalturaSessionType::ADMIN);
// media
$mediaObj = $client->media;
// Set a range to pull, order by last played at
$filter = new \KalturaMediaEntryFilter();
$filter->lastPlayedAtGreaterThanOrEqual = $startDate;
$filter->lastPlayedAtLessThanOrEqual = $endDate;
$filter->orderBy = '+lastPlayedAt';
// We still want more records
$pager = new \KalturaFilterPager();
$pager->pageSize = $pageSize;
// now list.....
$arr = $mediaObj->listAction($filter, $pager)->objects;
$buf = array();
foreach($arr as $k => $v) {
$t = array();
$t['dataUrl'] = $v->dataUrl;
$t['flavorParamsIds'] = $v->flavorParamsIds;
$t['plays'] = $v->plays;
$t['views'] = $v->views;
$t['lastPlayedAt'] = $v->lastPlayedAt;
$buf[] = $t;
}
return $buf;
}
You're iterating on the first page of each response, there might be more that one page.
The kaltura ListResponse has a totalCount property.
so you code should something like:
$pager = new \KalturaFilterPager();
$pageIndex = 1;
$entriesGot = 0;
$buf = array();
do
{
$pager->pageSize = $pageSize;
$pager->pageIndex = $pageIndex++;
// now list.....
$response = $mediaObj->listAction($filter, $pager);
$arr = $response->objects;
$entriesGot += count($arr);
foreach($arr as $k => $v) {
$t = array();
$t['dataUrl'] = $v->dataUrl;
$t['flavorParamsIds'] = $v->flavorParamsIds;
$t['plays'] = $v->plays;
$t['views'] = $v->views;
$t['lastPlayedAt'] = $v->lastPlayedAt;
$buf[] = $t;
}
}while($entriesGot < $response->totalCount);

Trying to get property of non-object PHP Laravel

I know that this question in the tittle is asked WAYY too much in here, and I went thru most of them but still cant find a solution for my code.
function calculatingWages($project_id){
$start_date = '2017-05-01';
$end_date = '2017-12-31';
$project = Project::find($project_id);
$users = $project->users()->get();
$sumWage=0;
foreach ($users as $user){
$timesheetHours = $user->timesheets()->whereBetween('timesheets.date',[$start_date,$end_date])->sum('hours');
$wages = UserWage::whereBetween('start_date',[ $start_date,$end_date])->whereBetween('end_date',[ $start_date,$end_date])->get();
foreach ($wages as $wage){
$value = $wage->value;
$currency = $wage->currency;
$sumWage = extractMonthsAndCalculate($value,$currency, $timesheetHours, $start_date, $end_date);
}
return $sumWage;
}
}
function extractMonthsAndCalculate($value,$currency, $timesheetHours, $start_date, $end_date){
$start = Carbon::createFromFormat('Y-m-d',$start_date)->month;
$end = Carbon::createFromFormat('Y-m-d',$end_date)->month;
$diffOfMonths = $end - $start;
$sumWage = 0;
for ($i = $start; $i <= $diffOfMonths; $i++) {
$wageYear = Carbon::createFromFormat('Y-m-d',$start_date)->year;
$wageDay = Carbon::createFromDate($wageYear,$i,'01')->lastOfMonth()->toDateString();
$test = convertingALL($value,$currency,$timesheetHours,$wageDay);
}
return $sumWage;
}
function convertingALL($value, $currency, $timesheetHours, $date)
{
$currencyObj = Exchange::where('date',$date)->get()->first();
$currencyDate = $currencyObj->date;
$hourlyWage = 0;
$sumWage = 0;
if($currencyDate == $date) {
$dollar = $currencyObj->dollar_lek;
$euro = $currencyObj->euro_lek;
if ($currency == 'ALL') {
$sumWage = $value;
} elseif ($currency == 'USD') {
$sumWage = ($hourlyWage *$timesheetHours) * $dollar;
} else {
$sumWage = ($hourlyWage *$timesheetHours)* $euro;
}
}else{
$euro = 140;
$dollar = 136.4;
if ($currency == 'ALL') {
$sumWage = $value;
} elseif ($currency == 'USD') {
$sumWage = $value * $dollar;
} else {
$sumWage = $value * $euro;
}
}
return $sumWage;
}
it says that it cant get the property of a non object in line 468
this is line 467-468:
$currencyObj = Exchange::where('date',$date)->get()->first();
$currencyDate = $currencyObj->date;
when I dd $currencyDate it prints the date of it, tried to parse it using carbon but still same thing, where am I messing up?
You need to tell Eloquent that the date field contains a date (even though it seems obvious).
Docs: https://laravel.com/docs/5.4/eloquent-mutators#date-mutators
In your Exchange model you should have
class Exchange extends Model {
protected $dates = [ 'date' ];
On an unrelated note, ->get()->first() will pull every single result back from the database, then chuck all but one of them away. If you just call ->first() then you'll only get one result from the database; same end result but better for performance.

Change date from database into an array

I am wondering how to the change date from this
Db -> holiday -> holidayDate (type date) = 2015-01-01, 2015-01-03, 2015-02-19, 2015-03-21, 2015-04-03, 2015-05-01, 2015-05-14, 2015-05-16, 2015-06-02, 2015-07-17, 2015-07-18, 2015-08-17, 2015-09-24, 2015-10-14, 2015-12-25
Here is the code
$sql = "select * from holiday order by holidayDate ";
//echo $sql;
$ambil_data = mysql_query($sql);
if ($data = mysql_fetch_array($ambil_data))
{
$tglLibur2 = $data['holidayDate'];
}
else
{
echo mysql_error();
}
function selisihHari($tglAwal, $tglAkhir)
{
$tglLibur = array("'".$tglLibur2."'"); <= i just want to get this array from db
$pecah1 = explode("-", $tglAwal);
$date1 = $pecah1[2];
$month1 = $pecah1[1];
$year1 = $pecah1[0];
$pecah2 = explode("-", $tglAkhir);
$date2 = $pecah2[2];
$month2 = $pecah2[1];
$year2 = $pecah2[0];
$jd1 = GregorianToJD($month1, $date1, $year1);
$jd2 = GregorianToJD($month2, $date2, $year2);
$selisih = ($jd2 - $jd1);
$libur1 = 0;
$libur2 = 0;
$libur3 = 0;
for($i=1; $i<=$selisih; $i++)
{
$tanggal = mktime(0, 0, 0, $month1, $date1+$i, $year1);
$tglstr = date("Y-m-d", $tanggal);
if (in_array($tglstr, $tglLibur))
{
$libur1++;
}
if ((date("N", $tanggal) == 7))
{
$libur2++;
}
if ((date("N", $tanggal) == 6))
{
$libur3++;
}
}
return $selisih-$libur1-$libur2-$libur3;
}
into this
$tglLibur = array("2015-01-01","2015-01-03","2015-02-19",
"2015-03-21","2015-04-03","2015-05-01","2015-05-14","2015-05-16",
"2015-06-02","2015-07-17","2015-07-18","2015-08-17","2015-09-24",
"2015-10-14","2015-12-25");
First of all your function selisihHari doesn't have access to the variable tglLibur2 you're using inside it. So I'm thinking you didn't post your full code here. But what you're looking for can be done with the following code:
$tglLibur = array()
foreach($tglLibur2 as $date){
$tglLibur[] = $date;
}
But what you're doing in your fetch code doesn't make sense. You keep overwriting the same variable. To change that do the following:
$tglLibur2 = array();
if ($data = mysql_fetch_array($ambil_data))
{
$tglLibur2[] = $data['holidayDate'];
}
This should give you the array you're looking for. That way you can get rid of your function all together.
Assuming that you aren't looping through each row and that $data['holidayDate'] is a string of dates, comma delimited, just change:
$tglLibur2 = $data['holidayDate'];
to
$tglLibur[] = explode(', ', $data['holidayDate']);

Number of intersections between 2 date ranges

I have 2 date ranges in my Codeigniter App, and i want to calculate the number of days that intersects between those to ranges. any ideas?
Date1start = YYYY-MM-DD;
Date1end = YYYY-MM-DD;
Date2start = YYYY-MM-DD;
Date2end = YYYY-MM-DD;
Something like this should work
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeEnd2 = new DateTime('2015-12-28');
// following http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
if ($datetimeStart1 < $datetimeEnd2 && $datetimeEnd1 > $datetimeStart2) {
echo min($datetimeEnd1,$datetimeEnd2)->diff(max($datetimeStart2,$datetimeStart1))->days+1;
} else {
echo 'no overlap';
}
Demo: http://3v4l.org/9Pecb
Only for PHP 5.2
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeStart1 = $datetimeStart1->format('U');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeEnd1 = $datetimeEnd1->format('U');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeStart2 = $datetimeStart2->format('U');
$datetimeEnd2 = new DateTime('2015-12-28');
$datetimeEnd2 = $datetimeEnd2->format('U');
// following http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
if ($datetimeStart1 < $datetimeEnd2 && $datetimeEnd1 > $datetimeStart2) {
echo round(
((min($datetimeEnd1,$datetimeEnd2)) - (max($datetimeStart2,$datetimeStart1))) / (60*60*24)) + 1;
} else {
echo 'no overlap';
}
Demo: http://3v4l.org/a1WLk
Write it easy:
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeEnd2 = new DateTime('2015-12-28');
$start = max($datetimeStart2,$datetimeStart1);
$end = min($datetimeEnd1,$datetimeEnd2);
echo $end >= $start ? $end->diff($start)->days+1 : "no overlap";

Sometimes the contents load and sometimes they don't

I have the script below and on the website http://cacrochester.com, sometimes the contents of the right sidebar load and sometimes they don't. I think it's if it's your first few times on a page, it will say no events scheduled.
I'm completely stumped on why this is happening. The data in the database is not changing.
Let me know if you need me to post anymore code.
Thanks for helping!
<?php
$dummy = 0;
$headingLength = 0;
$descriptionLength = 0;
$shortHeading = 0;
$shortDescription = 0;
$todayYear = date('Y');
$todayMonth = date('m');
$todayDay = date('d');
$events = new dates();
$noEvents = 0;
//get the number of upcoming events
$numEvents = $events->getNumberEvents();
//get the actual events
$results = $events->getRows();
//used if there are not at least 5 events to fill up the event scroller
switch($numEvents) {
case 1: $dummy = 4; break;
case 2: $dummy = 3; break;
case 3: $dummy = 2; break;
case 4: $dummy = 1; break;
}
//loops through all of the events in the table and adds them to the list
foreach($results as $result)
{
$strippedHeading = stripslashes($result['heading']);
$strippedDescription = stripslashes($result['description']);
$headingLength = strlen($strippedHeading);
$descriptionLength = strlen($strippedDescription);
$shortHeading = $strippedHeading;
$shortDescription = $strippedDescription;
$time = strftime("%l:%M %P", $result['time']);
$location = $result['location'];
$startDate = getdate($result['start_date']);
$today = getdate();
//if the events are NOT in the past...
if($startDate >= $today)
{
//if we are at the end of the array, add the class 'last' to the li
if(current($result) == end($result))
{
echo "<li class=\"last\"><h4>".$shortHeading."</h4><h6>$time</h6><h6>$location</h6></li>".PHP_EOL;
}
else
{
echo "<li><h4>".$shortHeading."</h4><h6>$time</h6><h6>$location</h6></li>".PHP_EOL;
}
$noEvents = 1;
}
//if there is not at least 5 events, it repeats the events in the list until there are 5 total
elseif($dummy > 0 && $numEvents > 0)
{
//if the events are NOT in the past...
if($startDate >= $today)
{
//if we are at the end of the array, add the class 'last' to the li
if($dummy == 0)
{
echo "<li class=\"last\"><h4>".$shortHeading."</h4> ".$shortDescription."</li>".PHP_EOL;
$dummy--;
}
else
{
echo "<li><h4>".$shortHeading."</h4> ".$shortDescription."</li>".PHP_EOL;
$dummy--;
}
//if we have 5 events, do not add anymore
if($dummy < 0)
{
break;
}
}
$noEvents = 1;
}
}
//if there are no events, display the no events message
if($noEvents == 0)
{
echo "<li class=\"last\"><h4>No Events Scheduled</h4></li>".PHP_EOL;
}
?>
When you do $startDate >= $today you are trying to compare two arrays, which isn't too good an idea. Just use plain timestamps and it should work fine:
$startDate = $result['start_date'];
$today = strtotime('today');
Also, I'm not sure if this is a typo: current($result) == end($result), but shouldn't it be $results, which is the array name?

Categories