Saturday 15 February 2020

PHP Tutorial | Easiest Way To Sort Date Array | KSORT



Code :-
<?php
$dates_array=array(
    "2020-01-5",
    "2020-01-10",
    "2018-03-4",
    "2019-01-15",
    "2020-01-2",
    "2020-05-3",
    "2020-01-9",
    "2020-02-8"
);

$new_array=array();
for ($i=0; $i < sizeof($dates_array); $i++)
{
    $new_array[ strtotime( $dates_array[$i] ) ]=$dates_array[$i];
}

ksort($new_array);

foreach ($new_array as $key => $value) {
    echo '<div>'.$value.'</div>';
}


?>
The following array is new_array :
<pre>
    <?php print_r($new_array);?>
</pre>

------------------------------------------------
Social Media Links :-

Subscribe my Channel:-
http://www.youtube.com/user/SanketRooney?sub_confirmation=1

Facebook Page:-
https://www.facebook.com/UnpossibleNS

Twitter Account:-
https://twitter.com/UnpossiblePOG

Blog :-
https://unpossiblepog.blogspot.in/
------------------------------------------------

Hey guys, this is UNPOSSIBLE POG.
In this video, I shall  show you the easiest way to sort date-array using PHP language.
As you can see, on left hand side, there is a code. and right hand displays an output in browser.
So there is a basic sort function in PHP which sorts array but only by character and not by dates.
Here., the “2nd january 2020” should be at first position followed by “3rd january 2020”.
So the sort function will not work in this case.
Now, we have to use new array with key-value pairs.
Let’s create a for loop and assign values in new array that we created.
But the code is not enough. What we should do is use strtotime function to convert date into integer. And use that integer as a key rather than 0,1,2,3 etc.
Now lets refresh, and you see each date with key-value pair where key is an integer value of that date.
Now we only have to do is to sort keys.
So there is a function called “ksort”.
If we use that and refresh it, it will sort all data by dates.
Lets try different years.
If you want to use sorted array, then use foreach loop.
The full code is in the description.
Thanks for watching.
Don’t forget to like, share and subscribe.