I have this, that doesnt work obviously.
$start = $hours->start{$day};
I need to be able the change the $day dynamically. $day can be any day of the week
//For example
$start = $hours->startSunday;
Let me try to be more clear. The following objects contain a certain time
// will echo something like 8:00am
echo $hours->startSunday;
//will echo something like 7:00am
echo $hours->startMonday;
I need to be able to change the day part dynamically with a variable, since it can be any day of the week.
//so something like
echo $hours->start.$day;
but that doesnt work
First. You could edit syntax with
$hours = new stdClass();
$day = 'Sunday';
$hours->{'start'.$day} = 10;
$start = $hours->{'start'.$day};
var_dump($start);
Secnod. Better ot use getter and setter methods.
class Hours
{
private $hours = array();
public function getStart($day)
{
return $this->hours[$day];
}
public function setStart($day, $value)
{
$this->hours[$day] = $value;
}
}
$hours = new Hours();
$day = 'Sunday';
$hours->setStart($day, 10);
$start = $hours->getStart($day);
var_dump($start);
You can use magic method, __get() and __set()
class Hours {
private $data = array();
public function __get($day) {
return $this->data[$day];
}
public function __set($day, $val) {
$this->data[$day] = $val;
}
}
$h = new Hours();
echo $hours->startMonday;
Related
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);
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.
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
I have had a hard time to get my head around this little piece of code.
protected function compressLowest($lowest){
$result = array();
$result['morning'] = array();
$result['afternoon'] = array();
$result['evening'] = array();
$result['allDay'] = array();
$type = $this->prices->getCondType();
$lastDate = 0;
$i = array();
$i['morning'] = $i['afternoon'] = $i['evening'] = $i['allDay'] = 0;
foreach($lowest as $date => $prices){
foreach($prices as $range => $price) {
if($this->isNextDay($date, $result[$range][$i[$range]]['to']) && $result[$range][$i[$range]]['price'] == $price){
$result[$range][$i[$range]]['to'] = $date;
} else {
$i[$range] = count($result[$range]);
$result[$range][] = array();
$result[$range][$i[$range]]['from'] = $date;
$result[$range][$i[$range]]['to'] = $date;
$result[$range][$i[$range]]['price'] = $price;
$result[$range][$i[$range]]['destime']=$this->arr['destime'];
$result[$range][$i[$range]]['deptime']=$this->arr['deptime'];
$result[$range][$i[$range]]['flight']=$this->arr['flight'];
}
}
$lastDate = $date;
}
//print_r($result);exit();
return $result;
}
And IsNextDay is checked as follows
protected function isNextDay($next, $day){
if($next - $day == 86400){ //60*60*24 = 86400
return true;
} else {
return false;
}
}
I can't figure out what is
isNextDay($date, $result[$range][$i[$range]]['to']) && $result[$range][$i[$range]]['price'] == $price) supposed to mean (the $day thing)?
in the if conditional clause of the second for-loop in the above function. Thank you if you could help me understand.
UPDATE
*Sorry I hadn't read it carefully until I discovered there was ) after the result[][]['to']... thanks for your concern.*
For the source code above, I always have a notice of UNDEFINED OFFSET 0. How to fix this bug-to-be ?
for your Undefined Offset 0 at the if line some index evaluates to 0 and the array you are using that index on does not have an element at that index.
For instance (I won't list all the possibilities) if $range is 0 and $result[0] is non-existent.
Can someone please show me how to do this basic thing using Zend Framework MVC?
I'm looping over the timestamp data and populating my table that way. i don't understand how I would pull my presentation HTML from this loop and stick it in the view? Any help would be greatly appreciated!
<table>
<?php
$day = date("j");
$month = date("m");
$year = date("Y");
$currentTimeStamp = strtotime("$year-$month-$day");
$numDays = date("t", $currentTimeStamp);
$counter = 0;
for($i = 1; $i < $numDays+1; $i++, $counter++)
{
$timeStamp = strtotime("$year-$month-$i");
if($i == 1)
{
// Workout when the first day of the month is
$firstDay = date("w", $timeStamp);
for($j = 0; $j < $firstDay; $j++, $counter++)
echo "<td> </td>";
}
if($counter % 7 == 0) {
echo "</tr><tr>";
}
echo "<td>" .$i . "</td>";
}
?>
</table>
I'm wanting to turn the above code into functions, but the HTML is throwing me off.
******Edited**** (mvc solution added)
Don't clutter your code with unnecessary functions, partials, etc. Why bother with HTML from the start, when you can create your data, then transform it into an HTML table? Here's the MVC sample (the following code suppose a one module project called 'default', modify accordingly if the project is module based) :
[listing 1] application/controller/IndexController.php
class IndexController extends Zend_Controller_Action {
public function indexAction() {
$this->view->calData = new Default_Model_Calendar('2010-07-17');
}
}
[listing 2] application/models/Calendar.php
class Default_Model_Calendar {
/* #var Zend_Date */
private $_date;
/* #param Zend_Date|string|int $date */
public function __construct($date) {
$this->_date = new Zend_Date($date);
}
/* #return Zend_Date */
public function getTime() {
return $this->_date;
}
public function getData() {
// normally, fetch data from Db
// array( day_of_month => event_html, ... )
return array(
1 => 'First day of month',
4 => '<span class="holiday">Independence Day</span>',
17 => '<img src="path/to/image.png" />'
//...
);
}
}
[lisging 3] application/view/scripts/index/index.phtml
echo $this->calendarTable($this->calData);
[listing 4] application/view/helpers/CalendarTable.php
class Default_View_Helper_CalendarTable extends Zend_View_Helper_Abstract {
private $_calData;
public function calendarTable($calData = null) {
if (null != $calData) {
$this->_calData = $calData;
}
return $this;
}
public function toString() {
$curDate = $this->_calDate->getTime();
$firstDay = clone $curDate(); // clone a copy to modify it safely
$firstDay->set(Zend_Date::DAY, 1);
$firstWeekDay = $firstDay->get(Zend_Date::WEEKDAY);
$numDays = $curDate->get(Zend_Date::MONTH_DAYS);
// start with an array of empty items for the first $firstweekDay of the month
$cal = array_fill(0, $firstweekDay, ' ');
// fill the rest of the array with the day number of the month using some data if provided
$calData = $this->_calData->getData();
for ($i=1; $i<=$numDays; $i++) {
$dayHtml = '<span class="day-of-month">' . $i . '</span>';
if (isset($calData[$i])) {
$dayHtml .= $calData[$i];
}
$cal[] = $dayHtml;
}
// pad the array with empty items for the remaining days of the month
//$cal = array_pad($cal, count($cal) + (count($cal) % 7) - 1, ' ');
$cal = array_pad($cal, 42, ' '); // OR a calendar has 42 cells in total...
// split the array in chunks (weeks)
$calTable = array_chunk($cal, 7);
// for each chunks, replace them with a string of cells
foreach ($calTable as & $row) {
$row = implode('</td><td>', $row);
}
// finalize $cal to create actual rows...
$calTable = implode('</td></tr><tr><td>', $calTable);
return '<table class="calendar"><tr><td>' . $calTable . '</td></tr></table>';
}
public function __toString() {
return $this->__toString();
}
}
With this code, you can even set exactly what you want within the $cal array before calling array_chunk on it. For example, $cal[] = $dayHtml . 'more';
This also follow true MVC as data (in Default_Model_Calendar) and view (in Default_View_Helper_CalendarTable) are completely separated, giving you the freedom to use any other model with the view helper, or simply not using any view helper with your model!