Change date from database into an array - php

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

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

php counter on mysql results

I got this simple foreach loop and can't figure out where is the problem with counter.
I get results like this. I am trying to make counter enlarged for one if it meets the conditions.
$building = 5;
$todaysdate = date("Y-m-d");
$tomorrows_date = date("Y-m-d", strtotime($todaysdate . "+1 days"));
$ends_date = "2018-04-30";
$counter = 0;
$query = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC"; // results give me numbers from 30 to 110.
$querydone = $db->query($query);
while($row = $querydone->fetch_assoc()) {
$every_id[$row['sifra']] = $row;
}
$firstday = new DateTime($tomorrows_date);
$lastday = new DateTime($ends_date);
for($q = $firstday; $q <= $lastday; $q->modify('+1 day')){
$result_day = $q->format("Y-m-d");
$i = 0; // counter for every value from mysql
foreach ($every_id as $key => $value) {
$counter = ${$i++} = $value['sifra'];
if($building >= $i) {
$valuesResult = "('$result_day','$counter')" . "<br />";
} else {
break;
}
echo $valuesResult;
}
}
Where am I wrong?
$building = 5;
$todaysdate = date("Y-m-d");
$tomorrows_date = date("Y-m-d", strtotime($todaysdate . "+1 days"));
$ends_date = "2018-04-30";
$counter = 0;
$query = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT 80"; // results give me numbers from 30 to 110.
$querydone = $db->query($query);
while($row = $querydone->fetch_assoc()) {
$every_id = $row['sifra'];
}
$firstday = new DateTime($tomorrows_date);
$lastday = new DateTime($ends_date);
for($q = $firstday; $q <= $lastday; $q->modify('+1 day')){
$result_day = $q->format("Y-m-d");
$i = 0; // counter for every value from mysql
foreach ($every_id as $key => $value) {
$counter = $i++;
if($building >= $i) {
$valuesResult = "('$result_day','$counter')" . "<br />";
} else {
break;
}
echo $valuesResult;
}
}

how to fetch value from post method and explode in foreach loop

how to fetch value from post method and explode in foreach loop.
public function generate_all_payslip() {
$data['title'] = "Generate All Payslip";
$this->payroll_model->_table_name = "tbl_department"; //table name
$this->payroll_model->_order_by = "department_id";
$all_dept_info = $this->payroll_model->get();
// get all department info and designation info
$dataalldep = array();
foreach ($all_dept_info as $v_dept_info) {
$dataalldep['all_department_info'][] = $this->payroll_model->get_add_department_by_id($v_dept_info->department_id);
}
foreach ($dataalldep['all_department_info'] as $keyemp=>$valemparray) {
$datae = array();
foreach($valemparray as $k=>$v) {
$datae['flag'] = 1;
$datae['designations_id'] = $v->designations_id;
$this->input->post('gapsbtn', TRUE);
$dataee['payment_date'] = $this->input->post('payment_date', TRUE);
$datepaymentmades = explode("-",$dataee['payment_date']);
$currentyears = $datepaymentmades[0];
$currentmonths = $datepaymentmades[1];
$currentyear = $currentyears ;
$currentmonth = $currentmonths ;
$datae['payment_date'] = $currentyear."-".$currentmonth;
$datae['employee_info'] = $this->payroll_model->get_emp_salary_list($emp = NULL, $datae['designations_id']);
$basicwagessalaey = $datae['employee_info'][0]->basic_salary;
$gross = $datae['employee_info'][0]->house_rent_allowance + $datae['employee_info'][0]->medical_allowance + $datae['employee_info'][0]->special_allowance + $datae['employee_info'][0]->fuel_allowance + $datae['employee_info'][0]->phone_bill_allowance + $datae['employee_info'][0]->other_allowance;
$deduction = $datae['employee_info'][0]->tax_deduction + $datae['employee_info'][0]->provident_fund + $datae['employee_info'][0]->other_deduction;
$net_extra = $gross - $deduction;
$workingdayscurrentmonth = $this->countDays($currentyear,$currentmonth, array(0));
$perdaysaaryperuser = $basicwagessalaey/30;
### full day ###
$queryfullday = $this->db->query("SELECT count(attendance_id) AS present_days FROM `tbl_attendance` WHERE attendance_status='1' AND month(date) = $currentmonth and year(date) = $currentyear AND employee_id='".$data['employee_info'][0]->employee_id."'");
$attendancecountarray = $queryfullday->result_array();
$attendancecounting = $attendancecountarray[0]['present_days'];
//$attendancecounting = 24;
$data['attendancecounting'] = $attendancecountarray[0]['present_days'];
if ($attendancecounting == $workingdayscurrentmonth) {
$data['totalmonthwagesfullday'] = ($perdaysaaryperuser*30)+$perdaysaaryperuser;
} else {
if ($workingdayscurrentmonth == 27) {
$data['totalmonthwagesfullday'] = ($perdaysaaryperuser*$attendancecounting)+($perdaysaaryperuser*3);
}
if ($workingdayscurrentmonth == 26) {
$data['totalmonthwagesfullday'] = ($perdaysaaryperuser*$attendancecounting)+($perdaysaaryperuser*4);
}
if ($workingdayscurrentmonth == 25) {
$data['totalmonthwagesfullday'] = ($perdaysaaryperuser*$attendancecounting)+($perdaysaaryperuser*5);
}
if ($workingdayscurrentmonth == 24) {
$data['totalmonthwagesfullday'] = ($perdaysaaryperuser*$attendancecounting)+($perdaysaaryperuser*6);
}
}
### half day ###
$queryhalfday = $this->db->query("SELECT count(attendance_id) AS present_days FROM `tbl_attendance` WHERE attendance_status='2' AND month(date) = $currentmonth and year(date) = $currentyear AND employee_id='".$data['employee_info'][0]->employee_id."'");
$attendancecountarray_half = $queryhalfday->result_array();
$attendancecounting_half = $attendancecountarray_half[0]['present_days'];
//$attendancecounting_half = 1;
$data['attendancecounting_half'] = $attendancecountarray_half[0]['present_days'];
$data['totalmonthwages_half'] = ($perdaysaaryperuser/2)*$attendancecounting_half;
### leave day ###
$queryleave = $this->db->query("SELECT count(attendance_id) AS present_days FROM `tbl_attendance` WHERE attendance_status='3' AND month(date) = $currentmonth and year(date) = $currentyear AND employee_id='".$data['employee_info'][0]->employee_id."'");
$attendancecountarray_leave = $queryleave->result_array();
$attendancecounting_leave = $attendancecountarray_leave[0]['present_days'];
//$attendancecounting_leave = 2;
$data['attendancecounting_leave'] = $attendancecountarray_leave[0]['present_days'];
$data['totalmonthwages_leave'] = $perdaysaaryperuser*$attendancecounting_leave;
### absent day ###
$queryabsent = $this->db->query("SELECT count(attendance_id) AS present_days FROM `tbl_attendance` WHERE attendance_status='0' AND month(date) = $currentmonth and year(date) = $currentyear AND employee_id='".$data['employee_info'][0]->employee_id."'");
$attendancecountarray_absent = $queryabsent->result_array();
$attendancecounting_absent = $attendancecountarray_absent[0]['present_days'];
//$attendancecounting_absent = 1;
$data['attendancecounting_absent'] = $attendancecountarray_absent[0]['present_days'];
$data['totalmonthwages_absent'] = $perdaysaaryperuser*$attendancecounting_absent;
######################
$querylastsalary = $this->db->query("SELECT * FROM `tbl_salary_payment` WHERE employee_id='".$data['employee_info'][0]->employee_id."' Order BY salary_payment_id desc LIMIT 1");
$lastsalary = $querylastsalary->result_array();
$paymentamountlastmonth = $lastsalary[0]['payment_amount'];
$data['totalmonthwage'] = ($data['totalmonthwagesfullday']+$data['totalmonthwages_half']+$net_extra)-($data['totalmonthwages_absent']);
if ($paymentamountlastmonth < 0) {
$data['totalmonthwages'] = $data['totalmonthwage']+$paymentamountlastmonth;
} else {
$data['totalmonthwages'] = $data['totalmonthwage'];
}
########## insert into tbl_salary_payment ##########
if ($datae['employee_info'][0]->employee_id !="") {
$dbinsert = array();
$dbinsert['employee_id'] = $datae['employee_info'][0]->employee_id;
$dbinsert['basic_salary'] = $datae['employee_info'][0]->basic_salary;
$dbinsert['house_rent_allowance'] = $datae['employee_info'][0]->house_rent_allowance;
$dbinsert['medical_allowance'] = $datae['employee_info'][0]->medical_allowance;
$dbinsert['special_allowance'] = $datae['employee_info'][0]->special_allowance;
$dbinsert['fuel_allowance'] = $datae['employee_info'][0]->fuel_allowance;
$dbinsert['phone_bill_allowance'] = $datae['employee_info'][0]->phone_bill_allowance;
$dbinsert['other_allowance'] = $datae['employee_info'][0]->other_allowance;
$dbinsert['tax_deduction'] = $datae['employee_info'][0]->tax_deduction;
$dbinsert['provident_fund'] = $datae['employee_info'][0]->provident_fund;
$dbinsert['other_deduction'] = $datae['employee_info'][0]->other_deduction;
$dbinsert['payment_for_month'] = $datae['payment_date'];
$dbinsert['payment_type'] = 'Cash Payment';
$dbinsert['payment_date'] = date('Y-m-d H:i:s');
$dbinsert['payment_amount'] = round($totalmonthwages);
$dbinsert['present'] = $attendancecounting;
$dbinsert['halfday'] = $attendancecounting_half;
$dbinsert['leave'] = $attendancecounting_leave;
$dbinsert['absent'] = $attendancecounting_absent;
$insertedid = $this->payroll_model->insertpayrolldata($dbinsert);
####### insert into tbl_salary_payslip ###
$dbinsertpayslip = array();
$dbinsertpayslip['payslip_number'] = date('Ymd');
$dbinsertpayslip['salary_payment_id'] = $insertedid;
$this->payroll_model->insertpayslipdata($dbinsertpayslip);
}
}
}
$data['subview'] = $this->load->view('admin/payroll/generate_all_payslip', $data, TRUE);
$this->load->view('admin/_layout_main', $data);
}
error with this code only
$this->input->post('gapsbtn', TRUE);
$dataee['payment_date'] = $this->input->post('payment_date', TRUE);
$datepaymentmades = explode("-",$dataee['payment_date']);
$currentyears = $datepaymentmades[0];
$currentmonths = $datepaymentmades[1];
$currentyear = $currentyears ;
$currentmonth = $currentmonths ;
if I use
$currentyear = date('Y');
$currentmonth = date('m');
its work fine.but i want use date that i have selected not current system date
how do i correct this code. currently i see this error
This page isn’t workingexample.com is currently unable to handle this request.HTTP ERROR 500
Is there any specific resason to use below mentioned line?
$datepaymentmades = explode("-",$dataee['payment_date']);
Or you let us know what you want to do with this.
If you want month, date and year than please check below.
$paymentDate = strtotime($dataee['payment_date']);
$month = date("m",strtotime($paymentDate));
$year = date("Y",strtotime($paymentDate));
$day = date("d",strtotime($paymentDate));

Why my Cakephp web service query takes lot of time to return data?

I've got a web service which takes around 15 secs to return JSON response to front-end.My code looks like this:
Controller code:
public function getDetailReport($data){
$user_id = $data->user_id;
$test_id = $data->test_id;
$result_obj = new TestSetDetailResultTable();
$data_array = $result_obj->getDetailReportByUser($user_id, $test_id);
if($data_array['status'] == 1) {
echo $this->successMessage('successfully Executed',$data_array['record']);
} else {
echo $this->failMessage($data_array['error'],$data_array['message']);
}
exit;
}
Model code:
public function getDetailReportByUser($user_id,$test_id) {
$data_array = Array();
$subject_array = Array();
$answer_array = Array();
$topper_array = Array();
$percentile_array = Array();
$max_marks = 0;
$perc = 0;
$hrs = 0;
$mint = 0;
$sec = 0;
$query = new AppQuery();
$query->callProcedure('getSummaryResult',array($test_id,$user_id));
$row_list = $this->loadRowList($query);
if(count($row_list) > 0) {
$max_marks = $row_list[0]->maximum_marks;
$perc = $row_list[0]->percentage;
$query->callProcedure('getCompletedTestTime',array($user_id,$test_id));
$row_time = $this->loadRowList($query);
$query->callProcedure('getAllUserPerTest',array($test_id));
$row_user = $this->loadRowList($query);
if(count($row_time)> 0 && count($row_user) > 0) {
foreach ($row_list as $list) {
$item['test_name'] = $list->test_name;
$item['total_question'] = $list->total_question;
$item['right_answer'] = $list->right_answer;
$item['wrong_answer'] = $list->wrong_answer;
$item['question_attempted'] = $list->question_attempted;
$item['question_not_attempted'] = $list->question_not_attempted;
$item['positive_marks'] = $list->positive_marks;
$item['negative_marks'] = $list->negative_marks;
$item['obtaine'] = $list->obtaine;
$item['maximum_test_time'] = $list->maximum_test_time;
$item['maximum_marks'] = $list->maximum_marks;
$item['test_date'] = $list->test_date;
$number = floatval($list->obtaine)* 100 / intval($list->maximum_marks);
$item['percentage'] = number_format($number, 2, '.', ''); // upto 2 decimal places
$data_array['detail'] = $item;
}
$tmp = Array();
$hrs = $row_time[0]->spent_hours;
$mint = $row_time[0]->spent_minute;
$sec = $row_time[0]->spent_second;
$completed_minute = $row_time[0]->compeleted_minute;
$completed_second = $row_time[0]->compeleted_second;
if($completed_second < 0) {
$completed_second = -1 * $completed_second; // only removing - sign
}
$tmp = $this->calculateTime($hrs, $mint, $sec);
$tmp['compeleted_minute'] = $completed_minute;
$tmp['compeleted_second'] = $completed_second;
$data_array['time'] = $tmp;
foreach ($row_user as $list) {
$tem['total_user'] = $list->total_user;
$data_array['users'] = $tem;
}
// Now get The subject wise Result
$temp = Array();
$query->callProcedure('getTestResult',array($test_id,$user_id));
$subject_result = $this->loadRowList($query);
foreach ($subject_result as $res) {
$temp['subject_name']= $res->subject_name;
$temp['marks_obtained'] = $res->obtaine;
$temp['total_question'] = $res->total_question;
$temp['question_attempted'] = $res->question_attempted;
$temp['wrong_answer'] = $res->wrong_answer;
// $temp['total_spent_hours'] = $res->total_spent_hours;
// $temp['total_spent_minute'] = $res->total_spent_minute;
// $temp['total_spent_second'] = $res->total_spent_second;
$time_arr2 = $this->calculateTime($res->total_spent_hours, $res->total_spent_minute, $res->total_spent_second);
$temp['total_spent_hours'] = $time_arr2['hours'];
$temp['total_spent_minute'] = $time_arr2['minute'];;
$temp['total_spent_second'] = $time_arr2['second'];
$temp['max_marks'] = intval($res->total_question) * intval($res->positive_marks);
$subject_array[] = $temp;
}
$data_array['subject_result'] = $subject_array;
//>>>>>>>>>>> Now get Answer of Question with Time spent>>>>>>>>>>
$temp = Array();
$query->callProcedure('getAnswerwithTime',array($test_id,$user_id));
$answer_list = $this->loadRowList($query);
foreach ($answer_list as $res) {
$temp['question']= utf8_encode($res->question);
$temp['user_answer']= $res->user_answer;
$temp['correct_answer'] = $res->correct_answer;
$temp['spent_hours'] = $res->spent_hours;
$temp['spent_minute'] = $res->spent_minute;
$temp['spent_second'] = $res->spent_second;
$temp['obtaine'] = $res->obtaine;
$answer_array[] = $temp;
}
$data_array['answer_with_time'] = $answer_array;
/*>>>>>>>>End>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Topper result for Comparing>>>>>>>>>>>>>>>>*/
$temp = Array();
$query->callProcedure('getTopperResult',array($test_id));
$top_arr = $this->loadRowList($query);
foreach ($top_arr as $top) {
$temp['user_name'] = $top->user_name;
$temp['test_name'] = $top->test_name;
$temp['total_question'] = $top->total_question;
$temp['right_answer'] = $top->right_answer;
$temp['wrong_answer'] = $top->wrong_answer;
$temp['question_attempted'] = $top->question_attempted;
$temp['question_not_attempted'] = $top->question_not_attempted;
$temp['positive_marks'] = $top->positive_marks;
$temp['negative_marks'] = $top->negative_marks;
$temp['maximum_marks'] = $top->maximum_marks;
$temp['obtaine'] = $top->obtaine;
$temp['percentage'] = $top->percentage;
$temp['maximum_test_time'] = $top->maximum_test_time;
$temp['test_date'] = $top->test_date;
$timer = $this->calculateTime( $top->spent_hours, $top->spent_minute, $top->spent_second);
$temp['spent_hours'] = $timer['hours'];
$temp['spent_minute'] = $timer['minute'];
$temp['spent_second'] = $timer['second'];
$temp['completed_minute'] = $top->completed_minute;
$sec_var = $top->completed_second;
if($sec_var < 0) {
$sec_var = -1 * $sec_var;
}
$temp['completed_second'] = $sec_var;
$percentile = $this->getPercentileRank($test_id,$top->percentage,$top->maximum_marks);
$temp['percentile'] = $percentile; // percentile
// $temp['rank'] = intval($percentile); // Rank
$topper_array[] = $temp;
}
//>>>>>>>>>>>>>>>>>> topper array contain Topper Percentile,now we need to get Rank according to Percentile
$topper_array = $this->rank($topper_array);
$data_array['toppers_result'] = $topper_array;
/*>>>>>>>>>>>>>>For Topper Result>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Login user Percentile>>>>>>>>>>>>>>>>*/
$percentile = $this->getPercentileRank($test_id, $perc, $max_marks);
$percentile_array = $this->loginUserRank($topper_array, $percentile);
$data_array['percentile'] = $percentile_array;
/*>>>>>>>>>>>>>>For Login user Percentile End>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>Get subject Wise Time of Toppers >>>>>>>>>>>>>*/
$subject_wise_time = $this->getSubjectWiseTopperTime($test_id);
$data_array['subject_wise_topper_time'] = $subject_wise_time;
/*>>>>>>>>>Get subject Wise Time of Toppers End >>>>>>>>>>>>>*/
/*>>>>>>>>>Get Answer with Time of Toppers >>>>>>>>>>>>>*/
$topper_answer_with_time = $this->topperAnswerTime($test_id);
$data_array['topper_answer_with_time'] = $topper_answer_with_time;
/*>>>>>>>>>Get Answer with Time of Toppers Ends >>>>>>>>>>>>>*/
return $this->modelMessage(1,'non','success',$data_array); exit;
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
}
I'm trying to debug this code but I don't know what am I missing here.How can this take 15 secs of time to return response back? Have I done something wrong?
When you debug than calculate the needed times with microtime(true), my guess are the DB querys for instance:
$start=microtime(true);
$answer_list = $this->loadRowList($query);
$stop=microtime(true);
$neededTime=$stop-$start;
echo "Time for answer_list $neededTime s for query $query";
Than you see what need to longest time. Than look on your query an look on your database schema. In most cases you can solve that issue by adding some indices on your db table. You can "debug" the query with explain on sql level, this will show you if you use an index.

How do I populate an associative array in PHP one line at a time?

I have this array:
$crops[] = array(
'Type' => $type_name,
'Method' => $method_name,
'Crop' => $crop_name,
'SowDirect' => $direct_sow_date,
'SowTransplant' => $transplant_sow_date,
'Transplant' => $transplant_date,
'BeginHarvest' => $begin_harvest_date,
'EndHarvest' => $end_harvest_date
);
What I want is to add the key/value pairs one by one within some logic code:
$crops[] = array();
if($var1 == something) {
$crops['Type'] = $value1;
}
if($var2 == something) {
$crops['Method'] = $value2;
}else{
$crops['Crop'] = $value3;
}
Using the first way, I get this, which is what I want:
http://gardencalc.drivingpeace.com/grid_data.php
Using the second way, I get this, which is NOT what I want:
http://gardencalc.drivingpeace.com/grid_data1.php
How do I make example 2 work the same as example 1?
Update 4/18/14
The answer below did the trick. The main problem I was having (and the one I hoped your suggestion would fix) is that I'm manipulating a bunch of dates within my logic decisions, and I'm using date_add() & date_sub().
If I just print the dates within the code, it works fine and I get the changes I want.
However, if I manipulate dates, add them to the array as in your method, then print the array via JSON, none of the dates are changing.
Here's your modified array code where the dates still aren't changing:
<?php
$loc_id = 174;
$prob_id = 10;
#Include the connect.php file
include('connect.php');
#Connect to the database
//connection String
$connect = mysql_connect($hostname, $username, $password)
or die('Could not connect: ' . mysql_error());
//select database
mysql_select_db($database, $connect);
//Select The database
$bool = mysql_select_db($database, $connect);
if ($bool === False){
print "can't find $database";
}
$tempSQL = "SELECT * FROM prob_28 WHERE prob_id=$loc_id";
$temp = mysql_query($tempSQL) or die(mysql_error());
while($row = mysql_fetch_array( $temp )) {
$prob1_90 = $row['prob1_90'];
$prob1_50 = $row['prob1_50'];
$prob1_10 = $row['prob1_10'];
$prob2_10 = $row['prob2_10'];
$prob2_50 = $row['prob2_50'];
$prob2_90 = $row['prob2_90'];
}
//build the dates
if ($prob_id == "10"){
$first_frost_date = date_create(date("Y").'-'.substr($prob1_10,0,2).'-'.substr($prob1_10,2,2));
$last_frost_date = date_create(date("Y").'-'.substr($prob2_10,0,2).'-'.substr($prob2_10,2,2));
}elseif ($prob_id == "50"){
$first_frost_date = date_create(date("Y").'-'.substr($prob1_50,0,2).'-'.substr($prob1_50,2,2));
$last_frost_date = date_create(date("Y").'-'.substr($prob2_50,0,2).'-'.substr($prob2_50,2,2));
}else{
$first_frost_date = date_create(date("Y").'-'.substr($prob1_90,0,2).'-'.substr($prob1_90,2,2));
$last_frost_date = date_create(date("Y").'-'.substr($prob2_90,0,2).'-'.substr($prob2_90,2,2));
}
// get data and store in a json array
$query = "SELECT * FROM data ORDER BY data_id";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$curcrop = array();
$data_id = $row['data_id'];
$days_to_harvest = $row['days_2_harvest'];
$resolution = $row['resolution'];
//Get type name
$type_id = $row['type_id'];
$type = mysql_query("SELECT * FROM type WHERE type_id=$type_id") or die(mysql_error());
while($typerow = mysql_fetch_array( $type )) {
$curcrop['Type'] = $typerow['type_name'];
}
//Get planting method name
$method_id = $row['method_id'];
$method = mysql_query("SELECT * FROM method WHERE method_id=$method_id") or die(mysql_error());
while($methodrow = mysql_fetch_array( $method )) {
$curcrop['Method'] = $methodrow['method_name'];
}
//Get crop name
$crop_id = $row['crop_id'];
$crop = mysql_query("SELECT * FROM crop WHERE crop_id=$crop_id") or die(mysql_error());
while($croprow = mysql_fetch_array( $crop )) {
$curcrop['Crop'] = $croprow['crop_name'];
}
//calculate the direct sow date
//Only build real date if the planting method is direct sow
if ($method_id == 1){
//check if it's a fall or spring crop type
//spring date
if ($type_id == 1){
$direct_sow_date = $first_frost_date;
$date_int = $row['wks_b4_frost_2_sow'] * 7;
date_sub($direct_sow_date,date_interval_create_from_date_string("$date_int days"));
//fall date
}else{
$direct_sow_date = $last_frost_date;
$date_int = $row['wks_b4_first_frost'] * 7;
date_sub($direct_sow_date,date_interval_create_from_date_string("$date_int days"));
}
}else{
$direct_sow_date = null;
}
$curcrop['SowDirect'] = $direct_sow_date;
//calculate transplant date
if ($method_id == 2){
//check if it's a fall or spring crop type
//spring date
if ($type_id == 1){
$transplant_date = $first_frost_date;
$date_int = $row['wks_b4_last_frost_2_trans'] * 7;
date_sub($transplant_date,date_interval_create_from_date_string("$date_int days"));
//fall date
}else{
$transplant_date = $last_frost_date;
$date_int = $row['wks_b4_first_frost'] * 7;
date_sub($transplant_date,date_interval_create_from_date_string("$date_int days"));
}
}else{
$transplant_date = null;
}
//transplant sow date
if ($transplant_date != null){
$date_int_trans = $row['wks_2_grow_trans'] * 7;
date_sub($transplant_date,date_interval_create_from_date_string("$date_int_trans days"));
$curcrop['SowTransplant'] = $transplant_date;
date_add($transplant_date,date_interval_create_from_date_string("$date_int_trans days"));
}else{
$curcrop['SowTransplant'] = null;
}
$curcrop['Transplant'] = $transplant_date;
//begin harvest date
if ($method_id == 1 && $direct_sow_date != null){
date_add($direct_sow_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_sub($direct_sow_date,date_interval_create_from_date_string("$resolution days"));
$curcrop['BeginHarvest'] = $direct_sow_date;
date_sub($direct_sow_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_add($direct_sow_date,date_interval_create_from_date_string("$resolution days"));
}
if ($method_id == 2 && $transplant_date != null){
date_add($transplant_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_sub($transplant_date,date_interval_create_from_date_string("$resolution days"));
$curcrop['BeginHarvest'] = $transplant_date;
date_sub($transplant_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_add($transplant_date,date_interval_create_from_date_string("$resolution days"));
}
//end harvest date
if ($method_id == 1 && $direct_sow_date != null){
date_add($direct_sow_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_add($direct_sow_date,date_interval_create_from_date_string("$resolution days"));
$curcrop['EndHarvest'] = $direct_sow_date;
date_sub($direct_sow_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_sub($direct_sow_date,date_interval_create_from_date_string("$resolution days"));
date_add($direct_sow_date,date_interval_create_from_date_string("$date_int days"));
}
if ($method_id == 2 && $transplant_date != null){
date_add($transplant_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_add($transplant_date,date_interval_create_from_date_string("$resolution days"));
$curcrop['EndHarvest'] = $transplant_date;
date_sub($transplant_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_sub($transplant_date,date_interval_create_from_date_string("$resolution days"));
date_add($transplant_date,date_interval_create_from_date_string("$date_int days"));
}
$crops[] = $curcrop;
}
echo json_encode($crops);
?>
In the first example, you're appending an array of information to the $crops array, but in the second, you append an empty array to the $crops array, and then set a few keys in that same $crops array.
What you need to do is build your "current crop" array with the second method and then append that array to the $crops list, as before:
$curcrop = array();
if($var1 == something) {
$curcrop['Type'] = $value1;
}
if($var2 == something) {
$curcrop['Method'] = $value2;
}else{
$curcrop['Crop'] = $value3;
}
$crops[] = $curcrop;

Categories