Blog

How to sort a multi-dimensional array by value

Let there is an array as follow:

Array
(
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)

[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)

[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
)


If you are still on PHP 5.2 or earlier, you’ll have to define a sorting function first:

function sortByOrder($a, $b) {
return $a[‘order’] – $b[‘order’];
}

usort($myArray, ‘sortByOrder’);


Starting in PHP 5.3, you can use an anonymous function:

usort($myArray, function($a, $b) {
return $a[‘order’] – $b[‘order’];
});


And finally with PHP 7 you can use the “spaceship operator”:

usort($myArray, function($a, $b) {
return $a[‘order’] <=> $b[‘order’];
});


To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero – best explained below. You can also use this for sorting on sub-elements.

usort($myArray, function($a, $b) {
$retval = $a[‘order’] <=> $b[‘order’];
if ($retval == 0) {
$retval = $a[‘suborder’] <=> $b[‘suborder’];
if ($retval == 0) {
$retval = $a[‘details’][‘subsuborder’] <=> $b[‘details’][‘subsuborder’];
}
}
return $retval;
});


*If you need to retain key associations, use uasort() – see comparison of array sorting functions in the manual.

How to control ‘from’ and ‘to’ datepickers so that ‘from’ is always earlier than ‘to’

//Date Picker
$(“#datepicker_from”).datepicker({
format: ‘dd-mm-yyyy’,
autoclose: true,
showButtonPanel: true,
startDate: new Date()
}).on(‘changeDate’, function (selected) {
var startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate() + 1);
$(‘#datepicker_to’).datepicker(‘setStartDate’, startDate);
}).on(‘clearDate’, function (selected) {
$(‘#datepicker_to’).datepicker(‘setStartDate’,null);
});

$(“#datepicker_to”).datepicker({
format: ‘dd-mm-yyyy’,
autoclose: true,
startDate: new Date()
}).on(‘changeDate’, function (selected) {
var endDate = new Date(selected.date.valueOf());
$(‘#datepicker_from’).datepicker(‘setEndDate’, endDate);
}).on(‘clearDate’, function (selected) {
$(‘#datepicker_from’).datepicker(‘setEndDate’,null);
});

Select only one checkbox in a group

This snippet will:

Allow grouping like Radio buttons
Act like Radio
Allow unselecting all

// the selector will match all input controls of type :checkbox
// and attach a click event handler
$(“input:checkbox”).on(‘click’, function() {
// in the handler, ‘this’ refers to the box clicked on
var $box = $(this);
if ($box.is(“:checked”)) {
// the name of the box is retrieved using the .attr() method
// as it is assumed and expected to be immutable
var group = “input:checkbox[name='” + $box.attr(“name”) + “‘]”;
// the checked state of the group/box on the other hand will change
// and the current value is retrieved using .prop() method
$(group).prop(“checked”, false);
$box.prop(“checked”, true);
} else {
$box.prop(“checked”, false);
}
});

src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”&gt;

Fruits
type=”checkbox” class=”radio” value=”1″ name=”fooby[1][]” />Kiwi
type=”checkbox” class=”radio” value=”1″ name=”fooby[1][]” />Jackfruit
type=”checkbox” class=”radio” value=”1″ name=”fooby[1][]” />Mango

Animals
type=”checkbox” class=”radio” value=”1″ name=”fooby[2][]” />Tiger
type=”checkbox” class=”radio” value=”1″ name=”fooby[2][]” />Sloth
type=”checkbox” class=”radio” value=”1″ name=”fooby[2][]” />Cheetah

Use google map with dynamic coordinates in laravel

In form,

Create a div to show map.

In page script,

http://maps.google.com/maps/api/js?key=AIzaSyAJLUg2IEbAOp4gMqRoXpSnjV0w1FDfYNk&sensor=false

$(document).ready(function() {
//to display google map after changing bootstrap tab
$(“a[href=’#service-two’]”).on(‘shown.bs.tab’, function(){
google.maps.event.trigger(map, ‘resize’);

//init function after tab opens
var destination = $(“#searched_destination”).val(); //destination is searched keyword
setTimeout(executeQuery(destination), 3000);
});

// //normal init function
// google.maps.event.trigger(map, ‘resize’);
// var destination = $(“#searched_destination”).val(); //destination is searched keyword
// setTimeout(executeQuery(destination), 3000);
});

function executeQuery(destination) {
$.ajax({
url: ‘getlocations/’+destination, //URL is route to get locations that matches “destination”
success: function(data) {
console.log(data);
locations = data;
renderMap(locations);
}
});
}

function renderMap(locations) {
// google.maps.event.trigger(map, ‘resize’);
var map = new google.maps.Map(document.getElementById(‘map’), {
zoom: 10,
// center: new google.maps.LatLng(16.8978811, 96.17212638), //static center point
center: new google.maps.LatLng(locations[0][1], locations[0][2]), //dynamic center point
mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});

google.maps.event.addListener(marker, ‘click’, (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}

In routes,

Route::get(‘/getlocations/{destination}’, array(‘as’=>’/getlocations’, ‘uses’=>’Frontend\SearchController@getLocations’));

In SearchController,

public function getLocations($destination)
{
//start hotel search result
$hotelRepo = new HotelRepository();
$hotels = $hotelRepo->getHotelsByDestination($destination); //search hotel by destination keyword

$result = array();
$index = 0;
foreach($hotels as $hotel){
$result[$index][0] = ”.$hotel->name.”.”;
$result[$index][1] = $hotel->latitude;
$result[$index][2] = $hotel->longitude;
$index++;
}
//end hotel search result

return response()->json($result);
}

In HotelRepository,

public function getHotelsByDestination($name){
// $objs = Hotel::whereNull(‘deleted_at’)->where(‘name’, ‘LIKE’, “%$name%”)->get();

$objs = Hotel::whereHas(‘country’, function($query) use($name) {
$query->where(‘countries.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhereHas(‘city’, function($query) use($name) {
$query->where(‘cities.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhereHas(‘township’, function($query) use($name) {
$query->where(‘townships.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhere(‘name’,’LIKE’,’%’.$name.’%’)
->get();

return $objs;
}

 

Remark:

If center point is placed at the top left corner of the map::

– on event that tab is shown, resize the map and then call map init function.

Example::

InĀ $(document).ready(function(){});

$(“a[href=’#service-two’]”).on(‘shown.bs.tab’, function(){
google.maps.event.trigger(map, ‘resize’);

//init function after tab opens
var destination = $(“#searched_destination”).val();
setTimeout(executeQuery(destination), 3000);
});

How to search from “name” column of multiple tables with a keyword in Laravel Eloquent

public function getHotelsByDestination($name){
$objs = Hotel::whereHas(‘country’, function($query) use($name) {
$query->where(‘countries.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhereHas(‘city’, function($query) use($name) {
$query->where(‘cities.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhereHas(‘township’, function($query) use($name) {
$query->where(‘townships.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhere(‘name’,’LIKE’,’%’.$name.’%’)
->get();

return $objs;
}

/*
Explanation::
– There are four tables: hotels, countries, cities and townships which are related.
– User enters a search keyword
which can be a hotel_name, country_name, city_name or township_name.
– Search whether that keyword is in “name” column of countries,cities,townships,and hotels.
– Display “HOTELS” that match keyword as their name or country_name or city_name or township_name.
*/

How to paginate an array in Laravel

In Controller::

<?php

namespace App\Http\Controllers\Frontend;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class HomeController extends Controller
{
public function index(Request $request)
{
//start popular cities
$popularCityArray = array();
$cityRepo = new CityRepository();
$popularCityRepo = new PopularCityRepository();
$popular_cities = $popularCityRepo->getObjs();

foreach($popular_cities as $popular_city){
$cityObj = $cityRepo->getObjByID($popular_city->city_id);
$cityObj->order = $popular_city->order; //bind order to city obj
//add city obj to city array
array_push($popularCityArray, $cityObj);
}
//end popular cities

//start paginating popular cities array
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$col = new Collection($popularCityArray);
$perPage = 3;
$currentPageSearchResults = $col->slice(($currentPage – 1) * $perPage, $perPage)->all();
$popularCityEntries = new LengthAwarePaginator($currentPageSearchResults, count($col), $perPage);

$popularCityEntries->setPath($request->url());
$popularCityEntries->appends($request->except([‘page’]));
//end paginating popular cities array

return view(‘frontend.home’)
->with(‘popular_cities’,$popularCityEntries);
}
}

In View::
{!! $popular_cities->render() !!}

How to select data where today is between “from_date” and “to_date” columns

Here is sample query:

In repository,

public function getDataWhereTodayIsBetweenFromAndTo()
{
//get current date to check between from_date and to_date
//you will need to import Carbon
$today = Carbon::today()->toDateString();
$objs = DB::table(‘table_name’)
->select(DB::raw(‘id, max(amount) as maximum_amount’))
->whereNull(‘deleted_at’)
->where(‘from_date’,'<=’, $today)
->where(‘to_date’,’>=’, $today)
->groupBy(‘category_id’)->get();
return $objs;
}