按特定密钥从数据库中排序数组php

时间:2016-05-07 20:40:51

标签: php arrays sorting

我有以下数组称为帖子,其中包含来自我的数据库的数据:

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

我试图通过" post_id将它从最大到最小排序。"目前我使用以下代码:

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

但是,这不起作用。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您的问题是您使用 - &gt;访问数组元素而不是[]。改变这个:

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

对此:

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

答案 1 :(得分:0)

Ryan关于访问数组元素的“修正”“意味着好”,但它有语法错误,并且会出现一堆这些:

  

注意:使用未定义的常量post_id - 假设为'post_id'

此外,他的答案比需要的更复杂。因为您要对子数组中的第一列进行排序,所以可以使用rsort()并避免使用用户定义/自定义排序方法。亲眼看看:

代码:(Demo

$posts=[
    ['post_id'=>29,'user_id'=>2,'post_image_url'=>'images/w8y46ot7bsr3cpxhunq9lg2dkmf05jzvei1a.jpg'],
    ['post_id'=>41,'user_id'=>2,'post_image_url'=>'images/czmhng9j7qr0ite4d2w6obvl3p1k5yasxuf8.jpg'],
    ['post_id'=>42,'user_id'=>2,'post_image_url'=>'images/rk5e7yc9xolsd4mbnp6t2w0zaquf8i1j3ghv.jpg'],
    ['post_id'=>39,'user_id'=>2,'post_image_url'=>'images/wuvhtcyksmza70641n3xb5l2rqgdp8jefoi9.jpg'],
    ['post_id'=>40,'user_id'=>14,'post_image_url'=>'images/41io86ln7f9gcz3ep2dmvrjbya5k0wsxqthu.jpg']
];
rsort($posts);

var_export($posts);

输出:

array (
  0 => 
  array (
    'post_id' => 42,
    'user_id' => 2,
    'post_image_url' => 'images/rk5e7yc9xolsd4mbnp6t2w0zaquf8i1j3ghv.jpg',
  ),
  1 => 
  array (
    'post_id' => 41,
    'user_id' => 2,
    'post_image_url' => 'images/czmhng9j7qr0ite4d2w6obvl3p1k5yasxuf8.jpg',
  ),
  2 => 
  array (
    'post_id' => 40,
    'user_id' => 14,
    'post_image_url' => 'images/41io86ln7f9gcz3ep2dmvrjbya5k0wsxqthu.jpg',
  ),
  3 => 
  array (
    'post_id' => 39,
    'user_id' => 2,
    'post_image_url' => 'images/wuvhtcyksmza70641n3xb5l2rqgdp8jefoi9.jpg',
  ),
  4 => 
  array (
    'post_id' => 29,
    'user_id' => 2,
    'post_image_url' => 'images/w8y46ot7bsr3cpxhunq9lg2dkmf05jzvei1a.jpg',
  ),
)