-1

I have this array: $attachments = array();

Which is populated like this:

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;

I want to sort it by year so I tried that:

usort($attachments,function($first,$second){
    return $first->year < $second->year;
});

But its not working:

Before

unsorted:Array (
[0] => Array ( [year] => 2018 [id] => 14689 )
1 => Array ( [year] => 2017 [id] => 14690 )
2 => Array ( [year] => 2018 [id] => 14688 )
[3] => Array ( [year] => 2018 [id] => 14687 ) .....)

enter image description here

After

sorted:Array (
[0] => Array ( [year] => 2018 [id] => 14689 )
1 => Array ( [year] => 2018 [id] => 16323 )
2 => Array ( [year] => 2018 [id] => 21545 )

[3] => Array ( [year] => 2017 [id] => 14690 )

[4] => Array ( [year] => 2018 [id] => 12711 ) .....)

enter image description here

Community
  • 1
  • 1
dvn22
  • 151
  • 7
  • And why it is not working? Years are sorted – u_mulder Dec 07 '18 at 14:39
  • @u_mulder it is not sorted. please check updated post. – dvn22 Dec 07 '18 at 14:40
  • If you had error reporting turned on you would notice the messages `PHP Notice: Trying to get property 'year' of non-object in...` (https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) – Nigel Ren Dec 07 '18 at 14:45

1 Answers1

2

I think you are trying to sort arrays but you are using the fields as object properties $first->year.

Try using

usort($attachments, function ($first, $second) {
    return $first["year"] < $second["year"];
});

print_r($attachments);

Demo

The fourth bird
  • 96,715
  • 14
  • 35
  • 52