×
×
Sort Multidimensional Array by date in PHP
Sort Multidimensional Array by date in PHP
Published Feb 07,2022 by Kailash Singh
0 Comment 2481 Views
In this post, we are going to teach, how to Sort Multidimensional Array in ascending and descending order by date in PHP.
What is Multidimensional Array?
A Multidimensional Array is an array contains one or more arrays.
1) Sort Multidimensional Array in Ascending Order
<?php
$data[] = array('id' => 3, 'text' => 'Kailash Singh', 'date' => '2022-02-07 13:04:25');
$data[] = array('id' => 1, 'text' => 'Amit Singh', 'date' => '2022-02-07 16:04:24');
$data[] = array('id' => 2, 'text' => 'Elevenstech', 'date' => '2022-02-06 10:04:20');
usort($data, function($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
});
echo '<pre>'; print_r($data);
?>
2) Sort Multidimensional Array in Descending Order
<?php
$data[] = array('id' => 3, 'text' => 'Kailash Singh', 'date' => '2022-02-07 13:04:25');
$data[] = array('id' => 1, 'text' => 'Amit Singh', 'date' => '2022-02-07 16:04:24');
$data[] = array('id' => 2, 'text' => 'Elevenstech', 'date' => '2022-02-06 10:04:20');
usort($data, function($a, $b) {
return strtotime($b['date']) - strtotime($a['date']);
});
echo '<pre>'; print_r($data);
?>
What is an usort() function?
It is an array using a user-defined comparision function.
Comments ( 0 )
Elevenstech Web Tutorials
Elevenstech Web Tutorials helps you learn coding skills and enhance your skills you want.
As part of Elevenstech's Blog, Elevenstech Web Tutorials contributes to our mission of “helping people learn coding online”.
Read More
Newsletter
Subscribe to get the latest updates from Elevenstech Web Tutorials and stay up to date
Copyright 2018 - 2024 Elevenstech Web Tutorials All rights reserved.