I want to show current week's data. In databse I have some perticular date data I have fill the missing dates and in view page I am showing that by foreach loop because I want to set different values for them. But it is showing mutliple times data because of 2 foreach loop. I want to get result in one array. My code is:
public function cashflowdetails() {
$cashflow = CashModel::orderBy('payment_date','asc') ->get();
$cashflow_array = [];
$cashflowDate_array = [];
$now = Carbon::now();
if (Input::get('from') != '') {
$weekStartDate =Input::get('from') ;
}
else{
$weekStartDate = Carbon::now()->startOfWeek();
}
if (Input::get('to') != '') {
$weekEndDate = Input::get('to');
}
else{
$weekEndDate = Carbon::now()->endOfWeek()->addDay();
}
$period = CarbonPeriod::create($weekStartDate, $weekEndDate);
foreach ($period as $date) {
$dt = new DateTime($date->format("Y-m-d"));
if($dt->format('l')!= 'Sunday' && $dt->format('l')!= 'SUNDAY' && $dt->format('l')!= 'SATURDAY' && $dt->format('l')!= 'Saturday')
{
foreach($cashflow as $cash){
if($date->format("Y-m-d") === $cash->payment_date )
{
$dbData['id'] = $cash->id;
$dbData['payment_date'] = $cash->payment_date;
$d = new DateTime($cash->payment_date);
$dbData['day'] = $d->format('l');
$dbData['opening_balance'] = $cash->opening_balance;
$dbData['other_income'] = $cash->other_income;
$dbData['rent'] = $cash->rent;
$dbData['labour'] = $cash->labour;
$dbData['electricity'] = $cash->electricity;
$dbData['creditors'] = $cash->creditors;
$dbData['insurance'] = $cash->insurance;
$dbData['direct_debits'] = $cash->direct_debits;
$dbData['others'] = $cash->others;
$dbData['total_amount'] = $cash->total_amount;
$dbData['updated_at'] = $cash->updated_at;
$dbData['created_at'] = $cash->created_at;
print_r($cash->payment_date);
$cashflow_array[] = $dbData;
}
else{
$dbData['id'] = null;
$dbData['payment_date'] = $date->format("Y-m-d");
$d = new DateTime($date->format("Y-m-d"));
$dbData['day'] = $d->format('l');
$dbData['labour'] = 0;
$dbData['opening_balance'] = 0;
$dbData['other_income'] = 0;
$dbData['rent'] =0;
$dbData['electricity'] = 0;
$dbData['creditors'] = 0;
$dbData['insurance'] =0;
$dbData['direct_debits'] = 0;
$dbData['others'] = 0;
$dbData['total_amount'] = 0;
$dbData['updated_at'] = '';
$dbData['created_at'] = '';
$cashflowDate_array[] = $dbData;
}
//break;
}
}
}
$cashflow = array_replace($cashflowDate_array, $cashflow_array);
return $cashflow;
}
public function cashflowdetails() {
$cashflow = CashModel::orderBy('payment_date','asc') ->get();
$cashflow_array = [];
$cashflowDate_array = [];
$now = Carbon::now();
if (Input::get('from') != '') {
$weekStartDate =Input::get('from') ;
}
else{
$weekStartDate = Carbon::now()->startOfWeek();
}
if (Input::get('to') != '') {
$weekEndDate = Input::get('to');
}
else{
$weekEndDate = Carbon::now()->endOfWeek()->addDay();
}
$period = CarbonPeriod::create($weekStartDate, $weekEndDate);
foreach ($period as $date)
{
//add a flag to see if the code was executed or not
$isExecuted = false;
$dt = new DateTime($date->format("Y-m-d"));
if($dt->format('l')!= 'Sunday' && $dt->format('l')!= 'SUNDAY' && $dt->format('l')!= 'SATURDAY' && $dt->format('l')!= 'Saturday')
{
foreach($cashflow as $cash){
if( $date->format("Y-m-d") === $cash->payment_date )
{
$dbData['id'] = $cash->id;
$dbData['payment_date'] = $cash->payment_date;
$d = new DateTime($cash->payment_date);
$dbData['day'] = $d->format('l');
$dbData['opening_balance'] = $cash->opening_balance;
$dbData['other_income'] = $cash->other_income;
$dbData['rent'] = $cash->rent;
$dbData['labour'] = $cash->labour;
$dbData['electricity'] = $cash->electricity;
$dbData['creditors'] = $cash->creditors;
$dbData['insurance'] = $cash->insurance;
$dbData['direct_debits'] = $cash->direct_debits;
$dbData['others'] = $cash->others;
$dbData['total_amount'] = $cash->total_amount;
$dbData['updated_at'] = $cash->updated_at;
$dbData['created_at'] = $cash->created_at;
//if executed, assign it true
$isExecuted = true;
//psuh the values to array
$cashflow_array[] = $dbData;
//break the loop
break;
}
}
//if not found in database
if(!$isExecuted){
$dbData['id'] = NULL;
$dbData['payment_date'] = $date->format("Y-m-d");
$d = new DateTime($date->format("Y-m-d"));
$dbData['day'] = $d->format('l');
$dbData['labour'] = 0;
$dbData['opening_balance'] = 0;
$dbData['other_income'] = 0;
$dbData['rent'] =0;
$dbData['electricity'] = 0;
$dbData['creditors'] = 0;
$dbData['insurance'] =0;
$dbData['direct_debits'] = 0;
$dbData['others'] = 0;
$dbData['total_amount'] = 0;
$dbData['updated_at'] = '';
$dbData['created_at'] = '';
$cashflow_array[] = $dbData;
}
}
}
return $cashflow_array;
}
you can achieve it easily by using a variable storing your current date, and double checking if the date is repeating or not.
For example:
//all the below code goes inside the foreach($cashflow as $cash)
//declare variable
$flag = false;
$counter = 0;
if($counter == 0)
{
$dt = new DateTime($date->format("Y-m-d"));
$curDate = $dt;
}else{
$dt = new DateTime($date->format("Y-m-d"));
}
if($curDate == $dt && counter !=0)
{
$flag = true;
}
$counter++;
//on your if conditions if($dt->format('l')!= 'Sunday' && $dt->format('l')!= 'SUNDAY' && $dt->format('l')!= 'SATURDAY' && $dt->format('l')!= 'Saturday')
//please add the condition:
&& flag == false
Related
I would appreciate some guidance on the following issue. I am by no means an expert in php. The code below takes almost 10 seconds to execute! Is there anything I am doing that is wrong or bad practice?
$data = [];
$today = date("Y/m/d");
$ThisYear = Date('Y'); //get current Year
$ThisMonth = Date('m'); //get current month
$Tday = '01'; //first day of month
$Tmonth = '09'; //September
if (8 < $ThisMonth && $ThisMonth < 13) {
$AcYear = $ThisYear; }
else {
$AcYear = $ThisYear - 1; // sets start of academic year to be last year
}
$AcFullYear = $AcYear.'/'.$Tmonth.'/'.$Tday;
//find rank in all school
$students_rank = [];
$school_id = Student::model()->findByAttributes(['user_master_id' => Yii::app()->user->id])->school_master_id;
$criteria1 = new CDbCriteria;
$criteria1->with = array('user');
$criteria1->condition = "t.school_master_id=:school_master AND user.status ='1'";
$criteria1->params = array(':school_master' => $school_id);
$school_students_details = Student::model()->findAll($criteria1);
foreach ($school_students_details as $key => $value) {
$student_name = StudentDetails::model()->findByAttributes(['user_master_id' => $value->user_master_id]); //student details with year group
$criteria2 = new CDbCriteria;
$criteria2->with = array('homeworkMaster');
$criteria2->condition = "t.student_id=:student_id AND homeworkMaster.question_type_id<>:question_type_id";
$criteria2->params = array(':student_id' => $value->user_master_id, ':question_type_id' => 6);
$HW_assignment_track = HomeworkAssignmentTrack::model()->findAll($criteria2);
$total_HW = count((array)$HW_assignment_track);
$student_score = 0;
$student_rank = 0;
$student_total_score = 0;
$total_HW_marks = 0;
$under_deadline_HW = 0;
$criteria3 = new CDbCriteria();
$criteria3->condition = "student_id =:student_id AND status=:status AND created_at >= '$AcFullYear' AND created_at <= '$today'";
$criteria3->params = [':student_id' => $value->user_master_id, ':status' => 2];
$student_completed_HW = HomeworkStudentAnswere::model()->findAll($criteria3);
$i = 1;
foreach ($student_completed_HW as $s_c_h_K => $s_c_h_V) {
if ($s_c_h_V->homework->homework_type == 2) {
$total_HW -= 1;
} elseif ($s_c_h_V->homework->homework_type == 1) {
$HW_questions = HomeworkQuestion::model()->findAllByAttributes(['homework_master_id' => $s_c_h_V->homework_id, 'status' => 1]);
foreach ($HW_questions as $qKey => $qVal) {
if ($qVal->question_type_id ==3) {
$total_HW_marks += 2;
} else {
$total_HW_marks += $qVal->marks;
}
}
$assignment = HomeworkAssignmentTrack::model()->findByAttributes(['id' => $s_c_h_V->assignment_track_id]);
$homeworks_within_validate = Assignment::model()->findByPk($assignment->assignment_id);
if ($homeworks_within_validate->valid_date === '0' && $homeworks_within_validate->deadline >= date('Y-m-d')) {
$total_HW -= 1;
}
if ($homeworks_within_validate->valid_date === '1' || (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($s_c_h_V->created_at))) && ($homeworks_within_validate->deadline < date('Y-m-d')))) {
if ($s_c_h_V->review_status === '2') {
$student_total_score += $s_c_h_V->score;
}
}
$homework_submit = HomeworkCompleteNotification::model()->findByAttributes(['homework_id' => $s_c_h_V->homework_id, 'assignment_track_id' => $s_c_h_V->assignment_track_id, 'student_id' => $value->user_master_id]);
if (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($homework_submit->created_at))) && ($s_c_h_V->review_status === '2')) {
$under_deadline_HW += 10;
}
if ($total_HW_marks !=0) {
$student_score += round(($student_total_score / $total_HW_marks) * 100);
} else {
$student_score = 0;
}
}
$i += 1;
}
//add revision scores to rank score
$criteria4 = new CDbCriteria();
$criteria4->condition = "user_id =:user_id AND date_created >= '$AcFullYear' AND date_created <= '$today'";
$criteria4->params = [':user_id' => $value->user_master_id];
$revision_score = RevisionScores::model()->findAll($criteria4);
$sum = 0;
foreach($revision_score as $item) {
$sum += $item['score'];
} //end of adding revision scores
$students_rank[$key]['student_id'] = $value->user_master_id;
$students_rank[$key]['year_group'] = $student_name->year_group_id; //added year group to model array
if ($student_score > 0) {
$student_rank += round($student_score / $total_HW, 0) + $under_deadline_HW;
$students_rank[$key]['rank'] = $student_rank + $sum;
} else {
$students_rank[$key]['rank'] = $sum;
}
}
$model = $this->multid_sort($students_rank, 'rank');
$rank_score = round(array_column($model, 'rank', 'student_id')[Yii::app()->user->id],0);
$year_rank =[];
$current_st = StudentDetails::model()->findByAttributes(['user_master_id' => Yii::app()->user->id]);
$current_st_year = $current_st->year_group_id;
$rank_list = [];
foreach ($model as $key => $value) {
$rank_list[] = $value['student_id'];
if ($value['year_group'] == $current_st_year) {
$year_rank[] = $value['student_id'];
}
}
$user = Yii::app()->user->id;
$sch_position = array_search($user,$rank_list);
$yr_position = array_search($user,$year_rank);
$final_rank = $sch_position + 1;
$yr_rank = $yr_position + 1;
$sch_rank = $final_rank;
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($sch_rank %100) >= 11 && ($sch_rank%100) <= 13) {
$sc_abbreviation = 'th';
$yr_abbreviation = 'th';
} else {
$sc_abbreviation = $ends[$sch_rank % 10];
$yr_abbreviation = $ends[$yr_rank % 10];
}
$models = UserMaster::model()->findByPk(Yii::app()->user->id);
$year_name = $models->studentDetails->yearGroup->name;
$data['type'] = 'success';
$data['score'] = '<div>Ranking Score: '.$rank_score.'</div>';
$data['yr_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$yr_rank. '</span><sup class="script-top" id="year_rank_abb">' .$yr_abbreviation. '</sup></div><div id="year_name">In ' .$year_name. '</div>';
$data['school_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$sch_rank. '</span><sup class="script-top" id="year_rank_abb">' .$sc_abbreviation. '</sup></div><div id="year_name">In School</div>';
$data['rank_revise'] ='<div>'.$rank_score.'</div>';
$data['yr_rank_revise'] = '<span>'.$yr_rank.'</span><sup class="superscript" style="left:0">'.$yr_abbreviation.'</sup>';
$data['sch_rank_revise'] = '<span>'.$sch_rank.'</span><sup class="superscript" style="left:0">'.$sc_abbreviation.'</sup>';
$_SESSION['rank'] = $rank_score;
$_SESSION['accuracy'] = $rank_score;
echo json_encode($data);
exit;
The above is used in an Yii application. It runs perfectly fine on localhost, but on live site, takes over 10 seconds to execute.
Your help and guidance is appreciated.
Thank
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.
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));
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.
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']);