John55 John55 - 6 months ago 12
PHP Question

Sort Array From Database by Specific Key php

I have the following array called posts which consists of data from my database:

Array ( [post_id] => 29 [user_id] => 2 [post_image_url] => images/w8y46ot7bsr3cpxhunq9lg2dkmf05jzvei1a.jpg ) 1
Array ( [post_id] => 41 [user_id] => 2 [post_image_url] => images/czmhng9j7qr0ite4d2w6obvl3p1k5yasxuf8.jpg ) 1
Array ( [post_id] => 42 [user_id] => 2 [post_image_url] => images/rk5e7yc9xolsd4mbnp6t2w0zaquf8i1j3ghv.jpg ) 1
Array ( [post_id] => 39 [user_id] => 2 [post_image_url] => images/wuvhtcyksmza70641n3xb5l2rqgdp8jefoi9.jpg ) 1
Array ( [post_id] => 40 [user_id] => 14 [post_image_url] => images/41io86ln7f9gcz3ep2dmvrjbya5k0wsxqthu.jpg ) 1


I am trying to sort it from greatest to least by "post_id." Currently I am using the following code:

usort($posts, function($a, $b) {
return $a->post_id > $b->post_id ? -1 : 1;
});
foreach($posts as $i){
echo print_r($i). "<br>";
}


However, this is not working. Any help would be appreciated.

Answer

Your problem is that you are accessing the element of the array with -> as opposed to []. Change this:

usort($posts, function($a, $b) { 
    return $a->post_id > $b->post_id ? -1 : 1;
}); 

To this:

usort($posts, function($a, $b) { 
    return $a[post_id] > $b[post_id] ? -1 : 1;
});