Lavachart display count each months - php

Hello i need serious help cause i have tried all way and not find an answer... so i really want to display chart that count many data each month, ex january 2 data, febuary 3 data etc... pls look at this brother
public function lihatkeluhan(){
$halaman="tindaklayanan";
$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,tanggal,produk,username,area,masalah,status'))->get();
$keluhan_group = keluhan::select(DB::raw('id,tanggal,produk,username,area,masalah,status'))
->get()->groupBy(function($date) {
return Carbon::parse($date->tanggal)->format('m'); // grouping by months
});
foreach ($keluhan_group as $group) {
$count[] = count($group);
}
$bulan = array("Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des");
$count = Count($keluhan_list);
$population = Lava::DataTable();
$population->addDateColumn("Month")
->addNumberColumn('Keluhan');
foreach($keluhan_group as $group){
$population->addRow(["jan",$count]);
}
Lava::LineChart('Population', $population, [
'title' => 'Tahun : 2017',
'titleTextStyle' => [
'color' => '#212F3C',
'fontSize' => 14
]
]);
$keluhan_group used to group by month
$count result is number of data each month
But idk how to display on chart...
Btw $population->addDateColumn("Month") is not work, it not display month but year T_T

Replace your code from $keluhan_group to $population with below code and check.
here you need to pass array of month and count of that month
$keluhan_group = keluhan::select(DB::raw("COUNT(*) as count , MONTHNAME(created_at) as month"))
->orderBy("created_at")
->groupBy(DB::raw("month(created_at)"))
->get()->toArray();
$chart_array = array();
foreach($keluhan_group as $data){
$n_data = [];
array_push($n_data,$data['month'],$data['count']);
array_push($chart_array,$n_data);
}
$population = Lava::DataTable();
$population->addDateColumn("Month")
->addNumberColumn('Keluhan')
->addRow($chart_array);
hope this will Help.

see i have implemented chart using my 'User' tabel,
i was not having lavachart in my project so i have update it using http://itsolutionstuff.com/post/laravel-5-geo-chart-example-and-demo-using-lavacharts-packageexample.html
here is my controller code:
$users = Users::select(DB::raw("COUNT(*) as count , MONTHNAME(created_at) as month"))
->orderBy("created_at")
->groupBy(DB::raw("month(created_at)"))
->get()->toArray();
$chart_array = array();
foreach($users as $data){
$n_data = [];
array_push($n_data,$data['month'],$data['count']);
array_push($chart_array,$n_data);
}
$lava = new Lavacharts;
$popularity = $lava->DataTable();
$popularity->addStringColumn('Country')
->addNumberColumn('Popularity')
->addRows($chart_array);
$lava->LineChart('demochart', $popularity, [
'title' => 'Demo population count',
'animation' => [
'startup' => true,
'easing' => 'inAndOut'
],
'colors' => ['blue', '#F4C1D8']
]);
return view('welcome', ['lava' => $lava]);
and in my .blade file:
<div id="temps_div"></div>
<?= $lava->render('LineChart', 'demochart' , 'temps_div') ?>
Hope this will Help.

$companies=Company::all();
$start = (new DateTime('2017-01-01'))->modify('first day of this month');
$end = (new DateTime('2022-01-01'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('12 month');
$period = new DatePeriod($start, $interval, $end);
$lava = new Lavacharts; // See note below for Laravel
$finances = \Lava::DataTable();
$finances->addDateColumn('Year');
foreach($companies as $company)
{
$finances ->addNumberColumn($company->company_name." ".$company->company_location." total sales amount");
}
foreach ($period as $dt) {
$yeardate=$dt->format("Y-m-d");
$insertrow = array( $yeardate );
foreach($companies as $company)
{
$cmp= $company->company_name;
$loc= $company->company_location;
$companiesinfo[]=$cmp." ".$loc;
$databasename=$company->database_name;
\Config::set('database.connections.tenant.host', 'localhost');
\Config::set('database.connections.tenant.username','root');
\Config::set('database.connections.tenant.password', '');
\Config::set('database.connections.tenant.database', $databasename);
\Config::set('database.default', 'tenant');
DB::reconnect('tenant');
$calculatesalesofcompany=B2CFINAL::
select(DB::raw('sum(GrandTotal) as total'))
->where(DB::raw('YEAR(SaleDate)'), '=', $yeardate)
->first();
if($calculatesalesofcompany->total==null)
{
$calculatesalesofcompany->total=0;
}
array_push( $insertrow, $calculatesalesofcompany->total );
}
$finances ->addRow($insertrow);
}
\Lava::ComboChart('Finances2', $finances2, [
'title' => 'Company Performance',
'titleTextStyle' => [
'color' => 'rgb(123, 65, 89)',
'fontSize' => 16
],
'legend' => [
'position' => 'in'
],
'seriesType' => 'bars',
]);

Related

how to stop adding more data in array in foreach loop

i looping 2 array a date and the data
$rdate = $request->month; //<-- Requested month
$days = Carbon::create();
$days = $days->daysInMonth; //<-- Finding how much days in month
for ($i = 1; $i < $days; $i++) { //Looping Date
$date = $rdate . '-' . $i; //Making full Date with formate 'Y-m-d'
foreach ($games as $game) { //Looping game array have 3 collection ['game1', 'game2', 'game3']
$result = Result::whereDate('created_at', $date)->where('game', $game->name)->where('admin_id', $admin->id)->first(); // Query Results for getting perticular game with date
if ($result) { //Checking if current date haven't result
$r[] = [
'game' => $game->name,
'number' => $result->number
];
} else {
$r[] = [
'game' => $game->name,
'number' => '-'
];
}
}
$resultd[] = [
'date' => $date,
'results' => $r // i want to stop adding old data here
];
}
i am expecting this result
{"results":[{"date":"2020-08-1","results":[{"game":"game1","number":"-"},{"game":"game2","number":"-"},{"game":"game3","number":"-"}]},{"date":"2020-08-2","results":[{"game":"game1","number":"-"},{"game":"game2","number":"-"},{"game":"game3","number":"-"}]
What actually getting
Adding old $r to results array
How to fix it i am trying to break it but can't figure it out
I have some untested code, as I do not have your data but I think this code below should work, you may need to modify some code as needed.
$rdate = '2020-8';
$days = collect([1,2,3]);
$games = collect(['game1', 'game2', 'game3']);
return $days->map(function ($item) use ($rdate,$games) {
$date = $rdate.'-'.$item;
return [
"date" => $date,
"results" => $games->map(function ($g) use ($date) {
$result = Result::whereDate('created_at', $date)
->where('game', $g->name)
->where('admin_id', $admin->id)
->first();
return ['game' => $g->name,
'number' => $result ? $result->number : '-',
];
})
];
});

Push second array inside first array

I have two array containing some value.
$type = array("first", "second", "third");
$date = array(
0 => "2019-04-30",
1 => "2019-05-01",
2 => "2019-05-02",
3 => "2019-05-03"
);
I need output something like this:
[
type :first,
date: [
"2019-04-30": 1.2,
.....
]
]
But for some reason I am not getting in that format.
This is the code I have tried.
$newArr = array();
foreach($type as $tt) {
$newArr[]['type'] = $tt;
$newDate = array();
foreach ($date as $d) {
$newDate[$d] = 1.2;
}
$newArr[]['date'] = $newDate;
}
Can anybody show what I did mistake.
Thank You.
It just comes down to building the array and then adding it in the right order, this builds all of the data and adds it in one go at the end of the loop...
$newArr = array();
foreach($type as $tt) {
$newDate = array();
foreach ($date as $d) {
$newDate[$d] = 1.2;
}
$newArr[] = [ 'type' => $tt, 'date' => $newDate];
}
You could shorten it to this, but it doesn't really make much difference...
foreach($type as $tt) {
$newArr[] = [ 'type' => $tt, 'date' => array_fill_keys($date, 1.2)];
}
Lets make it more simple
$newArr = array();
$newdates = array();
foreach($dates as $date){
$newdates[$date] = 1.2;
}
foreach($type as $tt) {
$newArry[] = array("type"=>$tt,"date"=>$newdates);
}
You can use array_map and array_fill_keys for the desired result
$type = ["first", "second", "third"];
$date = [
0 => "2019-04-30",
1 => "2019-05-01",
2 => "2019-05-02",
3 => "2019-05-03"
];
$newArr = [];
array_map(function($t, $d) use ($date, &$newArr){
$newArr[] = [
'type' => $t,
'date' => array_fill_keys($date, 1.2)
];
}, $type, $date);

How to subtract two integer values from different tables

How can I decrement the value of population in cycles table by using the value of number_of_mortality in mortalities table to subtract the population?
For example
The have 2 data in cycles table
Id 1 - (Date range from September 3 to September 28) Population = 3000
Id 2 - (Date range from October 1 to November 5) Population = 9000
I user wants to put a number of mortality to cycle id 1 , so he/she go to mortality modal.
The user inputs the date and it belongs to the cycle id 1 date range. The value of number_of_mortality is 25. After the user inputs the data, he/she click the add to submit to database.
After the submit, The value of population of cycle id 1 will be decrease and it should be 8975 ( 9000 - 25 = 8975).
This is my controller
MortalityController.php (store)
public function store(Request $request)
{
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
));
$cycle = Cycle::select('id', 'date_start_raise')
->where('date_start_raise','<=',$request->get('date_input'))
->where('date_end_raise','>=',$request->get('date_input'))
->get();
$id = 0;
$chickenAge = 0;
$input= Carbon::parse($request->get('date_input'));
foreach($cycle as $value){
$id = $value->id;
}
if ($id) {
$start = Carbon::parse($value->date_start_raise);
$chickenAge = $start->diffInDays($input) ;
}
return Mortality::create([
'date_input' => request('date_input'),
'number_of_mortality' => request('number_of_mortality'),
'chicken_age' => $chickenAge,
'cause_of_death' => request('cause_of_death'),
'cycle_id' => $id,
'user_id' => Auth::id()
]);
}
I figured how to connect the mortalities table to cycles table by using dates but I don’t know how and where can I put the code in decrementing by using the number_of_mortality to subtract the population. Can you help me? Thanks
MortalityController.php (update)
public function update(Request $request, $id)
{
$mortality = Mortality::findOrFail($id);
//validate
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
) );
$mortality->update($request->all());
}
MortalityController.php (Destroy)
public function destroy($id)
{
$mortality = Mortality::findOrFail($id);
$mortality->delete();
}
You can use the decrement() method.
After successfully creating the mortality you can decrement the population in the cycle:
Store:
public function store(Request $request)
{
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
));
// Make sure you only get the correct cycle here
$cycle = Cycle::where('date_start_raise', '<=', $request->get('date_input'))
->where('date_end_raise', '>=', $request->get('date_input'))
->first();
$chickenAge = 0;
$input= Carbon::parse($request->get('date_input'));
if ($cycle) {
$start = Carbon::parse($cycle->date_start_raise);
$chickenAge = $start->diffInDays($input) ;
}
$mortality = Mortality::create([
'date_input' => request('date_input'),
'number_of_mortality' => request('number_of_mortality'),
'chicken_age' => $chickenAge,
'cause_of_death' => request('cause_of_death'),
'cycle_id' => $cycle->id ?? 0,
'user_id' => Auth::id()
]);
// decrement population after successfully creating the mortality
if ($cycle) {
$cycle->decrement('population', $mortality->number_of_mortality);
}
return mortality;
}
Update:
public function update(Request $request, $id)
{
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
));
$mortality = Mortality::findOrFail($id);
$oldNumberOfMortality = $mortality->number_of_mortality;
// fill the model with the new attributes
$mortality->fill($request->all());
// check if number_of_mortality was changed
if ($mortality->isDirty('number_of_mortality')) {
$cycle = $mortality->cycle;
$difference = $oldNumberOfMortality - $mortality->number_of_mortality;
// check if the difference is positive or negative and increment or decrement
if ($difference < 0) {
$cycle->decrement('population', abs($difference));
} elseif ($difference > 0) {
$cycle->increment('population', $difference);
}
}
$mortality->save();
return mortality;
}

How to increase the performance of this function

How to increase the performance of following function in phalcon framework. There are thousands of records in the table. I tried different ways, but I am stuck the point. How can I increase the efficiency and reduce the execution time. Following are two methods:
public function currentmonthAction()
{
$payload = $this->request->getJsonRawBody();
$this->setDB();
$ticketsmodel = new Tickets();
$fromcitycondition = "";
if( isset($payload->city->id) )
{
$fromcitycondition = "and fromcity='{$payload->city->id}'";
}
try{
$date = new \Datetime($payload->date);
$year = $date->format('Y');
$month = $date->format('m');
$month = '08';
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
/* result for all cities passenger */
$result = array();
// get all cities permutations
$tmpcitiesdata = array();
$rawresultset = Tickets::find (
array(
'columns' => 'fromcity,tocity',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) ". $fromcitycondition,
'group' => 'fromcity,tocity'
));
foreach ($rawresultset as $rawresult) {
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['fromcity'] = $rawresult->fromcity;
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['tocity'] = $rawresult->tocity;
}
//var_dump($rawresultset);
// get tickets sold based on cities combinations
$total = 0;
foreach ($tmpcitiesdata as $tmpcities) {
$rawresultset = Tickets::find (
array(
'columns' => 'customer',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity'],
'group' => 'customer'
));
$totalsoldRaw = count($rawresultset);
// get ticket cancellations
$rawresultset = Tickets::find (
array(
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (3) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity']
));
//make sure cancellations are tickets cancellations not booking cancellations
foreach($rawresultset as $rawresult)
{
$resultNumber = Tickets::find("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );
if( count($resultNumber) > 0 ){
$totalsoldRaw = $totalsoldRaw-1;
}
}
$total += $totalsoldRaw;
array_push($result, array('total' => $totalsoldRaw, 'fromcity' => Cities::findFirstById($tmpcities['fromcity'])->name, 'tocity' => Cities::findFirstById($tmpcities['tocity'])->name));
}
//sort result based on counts
arsort($result);
//cut result to max 6 cities
$result = array_slice($result, 0, 6);
$this->response->setContentType('application/json')
->setJsonContent(
array( 'totaltickets' => $total, "allcities" => $result )
);
$this->response->send();
return;
}
catch(\PDOException $e)
{
$this->response->setStatusCode('422','Invalid Payload');
$this->response->setContentType('application/json')
->setJsonContent(array(
'flash' => array(
'class' => 'danger',
'message' => $e->getMessage()
)
));
$this->response->send();
return;
}
}
Use count instead of count(result of find). Also are you sure in // get ticket cancellations you don't need group ? Then you can select all tickets for customers in 1,3 tickettype and then filter resultset.
Also can't your first $rawresulset can't be:
$rawresultset = Tickets::find (
array(
'columns' => 'customer,fromcity,tocity,tickettype ',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1,3)".$fromcitycondition
'group' => 'customer,fromcity,tocity'
));
?
$ticketCanccelations = $rawresultset->filter(function($row){
if($row->tickettype == 3) {
return $row;
}
});
$resultNumber = Tickets::count("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );

php code to send email using find function in forloop

I have startdate and end date in my table like below.
startdate = 2016-01-01
Enddate = 2016-06-20
Now i want to send email automatically before 1 month from end date.
everything is working fine...email is also sending..
But my problem is i want to send email to multiple users if there are 2 rows match in table with my conditions then email is gone to both the users.
But my code only send email to only single users..not all users.
I want email is gone to all users one by one.
public function certificateExpired()
{
$this->autoRender = False;
$this->loadModel('Certificate');
$data = $this->Certificate->find("all", array(
'recursive' => -1, // should be used with joins
'fields' => array('User.*', 'Certificate.*'),
'joins' => array(
array(
'table' => 'users',
'alias' => 'User',
'type' => 'LEFT',
'conditions' => array('User.id = Certificate.user_id')
)
),
'conditions' => array('Certificate.is_expirable' => 1,'Certificate.status' => 1)
));
foreach ($data as $row) {
$currentdate = date("Y-m-d");
$date = $row['Certificate']['end_date'];
$newdate = strtotime($date .' -1 months');
$enddate = date('Y-m-d', $newdate);
if ($currentdate >= $enddate) {
//For sending email
$data['email'] = $row['User']['email'];
$data['name'] = $row['User']['name'];
$data['document_name'] = $row['Certificate']['name'];
$data['templateid'] = 19;
$send_mail = $this->EmailFunctions->certificateExpiredTemplate($data);
if ($send_mail) {
$this->redirect(array('controller' => 'Dashboards', 'action' => 'shipperDashboard'));
}
}
}
}
foreach ($data as $row) {
$currentdate = date("Y-m-d");
$date = $row['Certificate']['end_date'];
$newdate = strtotime($date .' -1 months');
$enddate = date('Y-m-d', $newdate);
if ($currentdate >= $enddate) {
//For sending email
$data['email'] = $row['User']['email'];
$data['name'] = $row['User']['name'];
$data['document_name'] = $row['Certificate']['name'];
$data['templateid'] = 19;
$send_mail = $this->EmailFunctions->certificateExpiredTemplate($data);
}
}
$this->redirect(array('controller' => 'Dashboards', 'action' => 'shipperDashboard'));
Change the foreach loop as above.

Categories