I'm doing export but don't know how to foreach calculate
get the employee's total time worked and how much the total amount.
data is retrieved from the database
$data = Clocks::orderBy('updated_at', 'desc')->get();
$row = [];
foreach ($data as $index) {
$row[] = array(
'0' => $index->user_id,
'1' => $index->total_time,
'2' => $index->earned_amount,
'3' => $index->bonus_pay,
);
}
return (collect($row));
I want to output it like this
user time amount bonus
1 25:30 400 20
3 9:00 150
Please help me, thank you for viewing this article.
I found a way
$data = Clocks::groupBy('user_id')
->selectRaw('SEC_TO_TIME( SUM(time_to_sec(`total_time`))) as total_time,
SUM(`earned_amount`) as earned_amount,
SUM(`bonus_pay`) as bonus_pay, user_id')
->get();
Related
I'm trying to get best seller courses. but something is going wrong...
$items = DB::table('orders')->select('course_id', DB::raw('COUNT(course_id) as count'))
->groupBy('course_id')->orderBy("count", 'desc')->get();
$courseIds = [];
foreach($items as $item) {
array_push($courseIds, $item->course_id);
}
$bestSellings = Course::whereIn('id', $courseIds)->get();
So when i do dd on $courseIds i'm getting
array:3 [▼
0 => 4
1 => 1
2 => 2
]
and yes it's must be like that because most selling course is number 4 then goes number 1 and then number to but when i try dd on $bestSellings i'm getting 1 course then 2 course then 4 course : / why? what can i do?
If you are using MySQL, then you could use 'ORDER BY FIELD':
$fieldOrder = join(", ", $courseIds);
$bestSellings = Course::whereIn('id', $courseIds)
->orderByRaw("FIELD(id, $fieldOrder)")
->get();
See: https://www.mysqltutorial.org/mysql-order-by/ "Using MySQL ORDER BY clause to sort data using a custom list"
I have a sql server table, VATTable like this:
VatCode | VATRate | Description | Active
00 0 VAT Rate 0.00% 1
04 4 VAT Rate 4.00% 1
06 6 VAT Rate 6.00% 1
...
21 21 VAT Rate 21.00% 1
....
with this query
$query = "SELECT VatCode, VatRate, Description, 0 as Goods, 0 as eFees, 0 as pFees, 0 as sFees, 0 as VAT, 0 as Total from VATTable where active=1";
$result = sqlsrv_query($conn,$query);
I need to build a multidimensional array with such data, that looks like this:
$VATTable = array
(
'04'=> array(
'VATRate'=>'4',
'Desc'=>'VAT 4.00%',
'Goods'=>0,
'eFees'=>0,
'pFees'=>0,
'sFees'=>0,
'Taxable'=>0,
'VAT'=>0,
'Total'=>0
),
'06'=> array(
'VATRate'=>'06',
'Desc'=>'VAT 6.00%',
'Goods'=>0,
'eFees'=>0,
'pFees'=>0,
'sFees'=>0,
'Taxable'=>0,
'VAT'=>0,
'Total'=>0
),
'10'=> array(
'VATRate'=>'10',
'Desc'=>'VAT 10.00%',
'Goods'=>0,
'eFees'=>0,
'pFees'=>0,
'sFees'=>0,
'Taxable'=>0,
'VAT'=>0,
'Total'=>0
)
);
so to be able to manage it in the following way:
$vatCode='10';
$VATTable[$vatCode]['Goods']=15;
echo $VATTable[$vatCode]['Desc'].': '.$VATTable[$vatCode]['Goods'];
although my php knowledge is poor I think I have first to build the inner array and then use array_push to add to VATTable Array, but while searching for such solution,
I found some example where I understood (??) that perhaps this can be done while fetching the recordset, and I thought I could do in this way:
$VATTable = array();
while($row = sqlsrv_fetch_array($result))
{
$VATTable[$row['VATCode']]['VATRate']=$row['VATRate'];
$VATTable[$row['VATCode']]['Desc']=$row['Description'];
$VATTable[$row['VATCode']]['Goods']=$row['Goods'];
};
but it does not work.
can suggest solution?
Thanks
This should work:
while($row = sqlsrv_fetch_array($result)) {
$id = $row['VATCode'];
$VATTable[$id] = [
'VATRate' => $row['VATRate'],
'Desc' => $row['Description'],
'Goods' => $row['Goods'],
}
print_r($VATTable);
Also, you don't need the word "array" in php7.
You can use
$VATTable[$id] = [ ... ]
instead of
$VATTable[$id] = array( ... );
If you don't want to hardcode indexes:
while($row = sqlsrv_fetch_array($result)) {
$id = $row['VATCode'];
$VATTable[$id] = $row;
unset($VATTable[$id]['VATCode']);
}
while($row = sqlsrv_fetch_array($result))
{
$tempVariable = array (
'VATRate'=>$row['VATRate'],
'Desc' =>$row['Description'],
'Goods' =>$row['Goods'],
'eFees' =>$row['eFees'],
'pFees' =>$row['pFees'],
'sFees' =>$row['sFees'],
'Taxable'=>$row['Taxable'],
'VAT' =>$row['VAT'],
'Total' =>$row['Total']
);
$VATTable[$row['VatCode']] = $tempVariable;
};
Now $VATTable contains your multidimensional array
I have a Job model and a Visit model, a Job can have many Visit's. I have set up the relationships appropriately in my Models.
A Visit also belongs to a Supplier, so a Supplier can have many visits.
A subcontractor is a Supplier who has an engineer value of 0 in the database.
I want to return an associative array with the amount of Jobs raised per subcontractor, something like this:
$supplier_job_count = array(
'Subcontractor1' => 23,
'Subcontractor2' => 3,
'Subcontractor3' => 7,
'Subcontractor4'=> 0
);
Here is what I have:
$conditions = array();
// get all the visits in the database
$visits = $this->Job->Visit->find('all');
// extract all the visit id's
$visit_supplier_ids = Hash::extract($visits, '{n}.Visit.supplier_id'); // 11612 records
// get all the subcontractors in the database
$subcontractors = $this->Job->Visit->Supplier->find('all', array('order' => 'id ASC', 'conditions' => array('Supplier.engineer' => 0)));
// extract all the subcontractor id's
$subcontractor_ids = Hash::extract($subcontractors, '{n}.Supplier.id'); // 1288 records
// intersect arrays so we only want matching values from both, i.e. only want visits whose supplier is a subcontractor
$visit_subcontractors = array_values(array_intersect($visit_supplier_ids, $subcontractor_ids));
// find all visits who is a subcontractor id
$visits = $this->Job->Visit->find('all', array('conditions' => array('Visit.supplier_id' => $visit_subcontractors)));
// extract out the job id's for the subcontractor visits
$visit_jobs_ids = Hash::extract($visits, '{n}.Visit.job_id');
// pass the job id's to the conditions for the jobs
$conditions['Job.id'] = $visit_jobs_ids;
// get all subcontractor jobs
$subcontractor_jobs = $this->Job->find('all', array('conditions' => $conditions));
$subcontractor_job_count = array();
foreach ($subcontractors as $key => $value) {
// this is where I am getting stuck
$subcontractor_job_count[$value['Supplier.name']] = ));
}
I am sort of half way there, just struggling to get a count of how many jobs raised per subcontractor, any ideas?
I need one help. I need to insert multiple data as per some Json object value into table using PHP and MySQL. I am explaining my code below.
$commnt=[{
'day_id':2,
'comment':'vodka1'
},{
'day_id':3,
'comment':'vodka2'
}
]
$result=[{
'day_id':1,
'restaurant':'193'
},{
'day_id':2,
'restaurant':'193'
},{
'day_id':3,
'restaurant':'193'
}
]
Here i need to enter all data from both Json object into this below table as per day_id. I am explaining column of my table below.
db_details:
id day_id restaurant comment
Here my requirement is when day_id will same the respective comment field value will entry into table other wise the comment filed value will remain blank.The expected out put is given below.
id day_id restaurant comment
1 1 193
2 2 193 vodka1
3 3 193 vodka3
My query is given below.
$insertintodetails=mysqli_query($connect,'INSERT INTO db_details
(day_id,restaurant,comment) values ("'. $result.'","'.$result[$i]['restaurant'].'","'.$commnt[$i]['comment'].'")');
Here there may be many use cases,like both Json object length may be same or different but the comment should insert as per day_id otherwise it will remain blank. In my query i can not insert as per required. Please help me to resolve this issue.
$newArray = $insertintodetails = array();
foreach($result as $rs)
{
$newArray[$rs->day_id] = [
"`day_id`=>'{$rs->day_id}'",
"`restaurant`=>'{$rs->restaurant}'"
];
}
foreach($commnt as $rs){
$newArray[$rs->day_id][] = "`comment`='{$rs->comment}'";
}
foreach($newArray as $rs){
$insertintodetails[]=mysqli_query($connect,'INSERT INTO db_details SET '.implode(',',$rs));
}
I create an example from above your question detail. You can try below code. And it should work for you...
//For example taken array and convert it to JSON
$comment = json_encode(array(array('day_id' => '2', 'comment' => 'vodka1'), array('day_id' => '3', 'comment' => 'vodka2')));
$result = json_encode(array(array('day_id' => '1', 'restaurant' => '193'), array('day_id' => '2', 'restaurant' => '193'), array('day_id' => '3', 'restaurant' => '193')));
//Convert JSON to array...
$arrComment = json_decode($comment, true);
$arrResult = json_decode($result, true);
foreach($arrResult AS $keyResult => $dataResult){
$day_id = $dataResult['day_id'];//day_id
$restaurant = $dataResult['restaurant'];//rasturant
$strComment = '';//comment
//Check and extract comment value from multi dimensional comment($arrComment) array...
if($getComment = find_comment_with_dayid($arrComment, $day_id)){
$strComment = $getComment;
}
//Insert records...
$insertintodetails=mysqli_query($connect,'INSERT INTO db_details
(day_id, restaurant, comment) values ("'. $day_id .'","'. $restaurant .'","'. $strComment .'")');
}
//Function will return comment for matched day_id
function find_comment_with_dayid($arrComment, $fieldKey) {
foreach($arrComment as $indCommenr => $dataComment) {
//Check for day_id, matched then return comment...
if($dataComment['day_id'] == $fieldKey) return $dataComment['comment'];
}
return FALSE;
}
Here, I taken example array for avoid JSON issue reported on your question. Hope this work well!
I am making an application using CakePHP. I made an action which uses saveAll function.
And I thought it works well, because it doesn't need so much data, but it took over 3 minutes to save using saveAll, or other save function.
Does anyone find my mistakes?
phpMyadmin's columns:
id, rank, school_detail_id, total_score, school_name,
(there is about 300~400 data)
public function rank_update(){
$check_scores = $this->ClubScore->find('all', array('fields'=>array('id','total_score')));
$check_scores2 = Set::sort($check_scores, "{n}.ClubScore.total_score","DESC");
$rank_id=0;
$temp_score=0;
$temp = null;
$for_count=0;
foreach ($check_scores2 as $check_score):
if($temp_score != $check_score['ClubScore']['total_score']){
$rank_id++;
$temp_score = $check_score['ClubScore']['total_score'];
// make ranking by score. same score is same ranking.
}
$this->ClubScore->id = $check_score['ClubScore']['id'];
$this->ClubScore->saveField('rank', $rank_id);
endforeach;
}
Divide the query from foreach to simpler approach
get distinct total_score in desc order
$data = $this->ClubScore->find('all', array('fields'=>array('DISTINCT total_score'), 'order' => 'total_score DESC'));
and then simply save the key as rank for each total_score using updateAll and foreach
Thank you very much Abhishek and AgRizzo ,Nunser!!
Now, I've completely solved this problem. It takes only 1 or 2 seconds!!!!!
Here is the source code.
public function rank_update(){
$data = $this->ClubScore->find('all', array('fields'=>array('DISTINCT total_score'), 'order' => 'total_score DESC'));
$check_scores = $this->ClubScore->find('all', array('fields'=>array('id','total_score')));
$check_scores2 = Set::sort($check_scores, "{n}.ClubScore.total_score","DESC");
$ii = 0;
$temp = 0;
foreach($check_scores2 as $scores):
if($data[$ii]['ClubScore']['total_score']
== $scores['ClubScore']['total_score']){
$temp=$ii+1;
}else{
$ii++;
$temp=$ii+1;
}
$update_arr[] = array(
'ClubScore' => array(
'id' => $scores['ClubScore']['id'],
'rank' =>$temp,
)
);
endforeach;
$update_arr = Set::sort($update_arr, "{n}.ClubScore.id","ASC");
var_dump($update_arr);
foreach($update_arr as $update_arrs):
$this->ClubScore->updateAll(
array(
'ClubScore.rank' => $update_arrs['ClubScore']['rank'],
),
array(
'ClubScore.id' => $update_arrs['ClubScore']['id'],
)
);
endforeach;
}
Thank you very much.
Best regards.