Home > Enterprise >  How to order the arrays in the reverse order of their creation with php?
How to order the arrays in the reverse order of their creation with php?

Time:12-01

I see that there is a lot of documentation for ordering array, but all I find is for ordering existing values within an array.

In my case, I need to sort the array themselves, within a meta that includes multiple array. And I want to order them in the reverse order of their creation.

Example:


$datacomments = get_post_meta($product_id, 'propina5', false); 

echo print_r($datacomments);

//Result:

Array ( [0] => Array ( [date] => 30-11-2021 13:38 [id] => 2 [rating] => 4 [comment] => bala bla bla bla bla [perce] => 10 ) 

[1] => Array ( [date] => 30-11-2021 13:38 [id] => 2 [rating] => 4 [comment] => bala bla bla bla bla [perce] => 10 ) 

[2] => Array ( [date] => 30-11-2021 13:40 [id] => 2 [rating] => 5 [comment] => bla bla bla bla [perce] => 10 ) 

[3] => Array ( [date] => 30-11-2021 13:41 [id] => 2 [rating] => 3 [comment] => bla bla bla bla bla [perce] => 5 ) ) 1


I have 3 arrays the [0], [1], [2] and the [3] ordered by default as they were created. But I need to exactly order them in reverse order since my intention is that the most recent ones appear first and not the other way around.

Well I can't find documentation or can't see if it's there in either official php or w3school, where I usually look for how to sort in this case.

Any suggestion? From already thank you very much.

CodePudding user response:

$reversed = array_reverse($input);

Docs: https://www.php.net/manual/en/function.array-reverse.php

If this array was the result of an query from database, you can use ORDER BY syntax from sql to get exactly you need.

CodePudding user response:

This will sort by the date value of each subarray in descending order:

$arr = [
    [ 'date' => '29-11-2021 22:32', 'id' => 2, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ],
    [ 'date' => '29-11-2021 22:35', 'id' => 8, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ],
    [ 'date' => '29-11-2021 22:45', 'id' => 6, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ]
];

usort($arr, static fn(array $arr1, array $arr2): int => -($arr1['date'] <=> $arr2['date']));

The same code would also work for DateTime objects:

$arr = [
    [ 'date' => new DateTime('29-11-2021 22:32'), 'id' => 2, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ],
    [ 'date' => new DateTime('29-11-2021 22:35'), 'id' => 8, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ],
    [ 'date' => new DateTime('29-11-2021 22:45'), 'id' => 6, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ]
];

usort($arr, static fn(array $arr1, array $arr2): int => -($arr1['date'] <=> $arr2['date']));
  • Related