Sort Multidimensional Array by date in PHP

Kailash Singh

Sort Multidimensional Array by date in PHP

Published Feb 07,2022 by Kailash Singh

0 Comment     726 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 )


SEARCH POST HERE

Subscribe My YouTube Channel

Join Our Telegram Channel & Support Eachother

CATEGORIES

INTERVIEW QUESTIONS

PROJECT SOURCE CODE






POPULAR POSTS