我有这个数组:$attachments = array();
填充如下:
if (have_rows('attachments_items')):
while ( have_rows('attachments_items') ) : the_row();
$attachment_id = get_sub_field('fileattachment',false);
$year = get_sub_field('year',false);
if(is_null($year) || $year == 0){
$year=2018;
}
$attachments[$i]['year'] = (int)$year;
$attachments[$i]['id'] = $attachment_id;
$i++;
endwhile;
endif;
我想按年份对它进行排序,所以我尝试了:
usort($attachments,function($first,$second){
return $first->year < $second->year;
});
但它不起作用:
之前
unsorted:Array(
[0] =>数组([year] => 2018 [id] => 14689)
1 =>数组([year] => 2017 [id] => 14690)
2 =>数组([year] => 2018 [id] => 14688)
[3] =>数组([year] => 2018 [id] => 14687)...)
之后
sorted:Array(
[0] =>数组([year] => 2018 [id] => 14689)
1 =>数组([year] => 2018 [id] => 16323)
2 =>数组([year] => 2018 [id] => 21545)[3] =>数组([year] => 2017 [id] => 14690)
[4] =>数组([year] => 2018 [id] => 12711) .....)
答案 0 :(得分:2)
我认为您正在尝试对数组进行排序,但是您将字段用作对象属性$first->year
。
尝试使用
usort($attachments, function ($first, $second) {
return $first["year"] < $second["year"];
});
print_r($attachments);