Sorting arrays and comparing array values php - php

Good day guys, I'm working on plotting data on charts using ChartJs and Laravel, I need to plot data based on months and I want the whole 12 months showing on the chart even without data,
I have months in an array ['January', 'February'....
Then I have my data here:
$stats = DB::table('wallet_payouts')
->groupBy('date')
->orderBy('date', 'ASC')
->get([
DB::raw('DATE_FORMAT(created_at, "%M") as date'),
DB::raw('COUNT(*) as value')
]);
$labels = [];
$data = [];
foreach ($months as $month){
foreach ($stats as $stat){
if ($month == $stat->date){
array_push($labels, $stat->date);
array_push($data, $stat->value);
}else{
array_push($labels, $month);
array_push($data, 0);
}
}
}
But the issue is instead of 12 months after the loop I'm getting 24... Duplicates and the data also in 24... I want the months to just match with the data without the duplicates

Try the below code:
$stats = DB::table('wallet_payouts')
->groupBy('date')
->orderBy('date', 'ASC')
->get([
DB::raw('DATE_FORMAT(created_at, "%M") as date'),
DB::raw('COUNT(*) as value')
]);
$labels = $months;
$data = [];
$temp = [];
foreach ($stats as $stat){
$temp[$stat->date] = $stat->value;
}
foreach($months as $month){
if(array_key_exists($month,$temp)){
array_push($data, $temp[$month]);
} else {
array_push($data, 0);
}
}

Related

How to sort data between two dates using query() function in laravel

Here is my controller:
$my_query = Deathregister::query();
foreach ($request->query() as $key => $value)
{
$my_query->where($key, $value);
}
$my_query->get();
Now if i pass 'fromdate = 2020-10-30' and 'todate = 2021-11-07' i want all the data in bwtween these days. Is this possible?
You can use CarbonPeriod class of PHP.
To use it in Laravel
import it first
use Carbon\CarbonPeriod;
Then in the controller function use
$period = CarbonPeriod::create($request->from_dt,'1 day', $request->to_dt);
foreach ($period as $value) {
$reqDate = $value->format('d-M-Y');
//$reqDate will have the date you can change the format as per your requirement
}
You can use whereDate() method:
Deathregister::whereDate('date_field','>=', $request->input('fromdate'))
->whereDate('date_field','<=', $request->input('todate'))
->get();
The below code worked for me to sort date by given all the parameter with date.
$q = $request->query();
if ($q != NULL) {
$fromdate = $request->fromdate;
$todate = $request->todate;
$my_query = Movementregister::query();
if ($fromdate != NULL and $todate != NULL) {
if (!empty($q['type'])) {
$my_query->where('type', $q['type']);
}
if (!empty($q['issue'])) {
$my_query->where('issue', $q['issue']);
}
$my_query->whereBetween('created_at', [$fromdate, $todate]);
} else {
foreach ($request->query() as $key => $value) {
$my_query->where($key, $value);
}
}
$data = $my_query->get();
return response()->json(["message" => "Success", "data" => $data], 200);
}

When fetching data from table "add_hotels" but along with the required data i'm also getting some NULL arrays in Laravel

It is the result function inside the HotelController.
public function result()
{
$data=Input::except(array('_token'));
$city= $data['city'];
$cities_id = DB::table('cities')
->select('id')
->where('cities.city_name', 'LIKE', "%$city%")
->get();
$hotel = array();
foreach ($cities_id as $value) {
$i=$value->id;
$hotel[] = DB::table('add_hotels')
->select('id')
->where('city_id', '=', $i)
->get();
}
var_dump($hotel);
exit();
return view('hotel.result',compact('hotel','city'));
}
This is the result which i'm getting, but I required only data marked by red color box
Try this query:
$cities_id = DB::table('cities')
->where('cities.city_name', 'LIKE', "%$city%")
->Join('add_hotels','add_hotels.city_id','=','cities.id')
->select('add_hotels.id')
->get();
var_dump($cities_id);

Can I use case method append on Laravel5?

I write code like this
$category = Input::get('category'); // ?category=1
if(!empty($category)){ // ?category=1, category=2
$lists = \App\Test::where('created_at', '<=', 'now()')
->where('category', $category) // append this.
->orderBy('id','desc')
->get();
}
else { // ?category=, category=0
$lists = \App\Test::where('created_at', '<=', 'now()')
->orderBy('id','desc')
->get();
}
That is so work but I think dirty code.
I dont wanna write same code again if I can.
So I wish to do like this ( Not working )
$category = Input::get('category'); // ?category=1
$lists = \App\Test::where('created_at', '<=', 'now()');
if(!empty($category)){ // ?category=1, category=2
$lists .= $lists::where('category', $category);
}
$lists .= $lists::orderBy('id','desc')->get();
Anyone know kind solutions?
Use this code
$lists = \App\Test::where('created_at', '<=', 'now()');
if(!empty($category)){ // ?category=1, category=2
$lists = $lists->where('category', $category);
}
$lists->orderBy('id','desc')->get();
You can do it like:
$lists = \App\Test::where('created_at', '<=', 'now()');
and then when you want to append anything, add it like this:
if(!empty($category)){ // ?category=1, category=2
$lists = $lists::where('category','=', $category);
}
you don't need to use .

How to change a php array

Simple question to which I don't have an answer.
How can I change my array from this:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
to this:
[{"sku":"6","buyers":"7","base":"8"}]
I have three queries for three different database tables:
$sku = DB::table('mapiranje')->select(DB::raw('count(*) as sku'))
->where('mate_fk', '=', NULL)
->get();
$kupac = DB::table('mapkupci')->select(DB::raw('count(*) as buyers'))
->where('kupci_fk', '=', NULL)
->get();
$base = DB::table('dist_base')->select(DB::raw('count(*) as base'))
->where('base_fk', '=', NULL)
->get();
now each returns:
[{"sku":"6"}]
[{"buyers":"6"}]
[{"base":"6"}]
I have used merge_array to make a single array, but I get:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
what I want is:
[{"sku":"6","buyers":"7", "base":"8"}]
Refactor your code according to right Laravel way:
$result = [
'sku' => DB::table('mapiranje')->whereNull('mate_fk')->count(),
'buyers' => DB::table('mapkupci')->whereNull('kupci_fk')->count(),
'base' => DB::table('dist_base')->whereNull('base_fk')->count()
];
$result = [];
foreach($input as $oneInputRow) {
$result[$oneInputRow[0]] = $oneInputRow[1];
}
$target = array();
$start = array(array("sku"=>"6"), "buyers"=>"7"), "base"=>"8"));
foreach($start as $sub){
foreach($sub as $key => $val){
$target[$key] = $val;
}
}
Not shure if laravel provides any special syntax, but just with php I'd do it as above.
Basicly you loop over the start-array. In that you loop over every array to get the key/val combination and put that into the target-array.
For the second loop there would be other ways if you only have one entry in every secondary array.
Please try below code
$dd = '[{"sku":"6"},{"buyers":"7"},{"base":"8"}]';
$data = json_decode($dd,true);
$result = array();
foreach($data as $key=>$value){
foreach($value as $key1=>$value1){
$result[$key1] = $value1;
}
}
echo json_encode($result); //this will print your required format result

Increment value in array php

I am trying to make a function that grabs all the days that have events that are in a database for a certain user. For instance if there were two events on Jan 23, 2013 it would add Jan 23, 2013 to the array. I got it to work so it adds all the days (without adding the same day twice) but now I want to be able to say how many dates are on each day. So on Jan 23, 2013 it would say they have two events in that day.
I hope this makes sense... I have some code for further aid.
PHP Function (grabbing each day that has events)
//gets upcoming days that have events for a user
public function get_upcoming_days_with_events() {
$return_array = array();
$date_in=null;
$user_id = $this->session->userdata('id');
$query =$this->db->select()->from('events')->where('user_id', $user_id)->get();
foreach ($query->result_array() as $event => $row) {
$date = strtotime($row['date_due']);
if (sizeof($return_array) != 0) {
foreach ($return_array as $date_in_array => $row) {
$d = $row['full_date'];
if (date('Y-m-d', $date) == $d) {
//date is already in array
//increment the number of assignments on this day
$row['number_of_assignments'] += 1;
$date_in = true;
} else{
$date_in = false;
}
}
}
if ($date_in == false) {
$return_array[] = array(
'day' => date('d', $date),
'month' => date('m', $date),
'full_date' => date('Y-m-d', $date),
'number_of_assignments' => 1
);
}
}
return $return_array;
}
So with this I want to be able to increment $return_array['number_of_assignments'] if my function notices that a certain day has more than one event.
Let me know if you need any more info...
Thanks! :)
We can save the info in return_array by index of date, if the date info have not been set into return_array, we make an empty info. Each time, we simply increase number_of_assignments.
public function get_upcoming_days_with_events()
{
$return_array = array();
$user_id = $this->session->userdata('id');
$query =$this->db->select()->from('events')->where('user_id', $user_id)->get();
foreach ($query->result_array() as $event => $row)
{
$date = strtotime($row['date_due']);
$date_key = date('Y-m-d', $date);
if (!isset($return_array[$date_key]))
{
$new_item = array(
'day' => date('d', $date),
'month' => date('m', $date),
'full_date' => $date_key,
'number_of_assignments' => 0,
);
$return_array[$date_key] = $new_item;
}
$return_array[$date_key]['number_of_assignments']++;
}
$return_array = array_values($return_array);
return $return_array;
}
Function: array_count_values() can help you with this, it gives total number of occurance of a value in an array.
For example:
$a = array("apple", "banana", "apple");
var_dump(array_count_values($a));
Will output
array(
[apple] => 2,
[banana] => 1
);
So instead of trying to filter out duplicate events, add them all on the array and then use array_count_values() at last to know their occurenses.

Categories