T
T
TechnicalMan942020-11-26 14:40:09
PHP
TechnicalMan94, 2020-11-26 14:40:09

How to sort PHP multidimensional array with complex conditions?

Hello everyone

Given a PHP array, it contains 5 others

array
array(5) {
  [4]=>
  array(3) {
    ["autor_id"]=>
    int(4)
    ["count_msg"]=>
    int(5)
    ["last_date"]=>
    int(1606350743)
  }
  [2]=>
  array(3) {
    ["autor_id"]=>
    int(2)
    ["count_msg"]=>
    int(7)
    ["last_date"]=>
    int(1606350737)
  }
  [6]=>
  array(3) {
    ["autor_id"]=>
    int(6)
    ["count_msg"]=>
    int(29)
    ["last_date"]=>
    int(1606350733)
  }
  [1]=>
  array(4) {
    ["autor_id"]=>
    int(1)
    ["count_msg"]=>
    int(36)
    ["last_date"]=>
    int(1606350726)
    ["unread_pm"]=>
    int(1)
  }
  [3]=>
  array(3) {
    ["autor_id"]=>
    int(3)
    ["count_msg"]=>
    int(8)
    ["last_date"]=>
    int(1606349427)
  }
}


It is required to sort the array in such a way that the first are those in which ['unread_pm'] is present (no matter what value), then those that do not have this value.

All this is sorted globally by ['last_date'].

In general, these are 5 dialogs with visitors, in one of them there is 1 unread message (you need to move it up), everything else is down by date. At the top, dialogues with unread ones are also sorted by date among themselves.

Is it even real?)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nokimaro, 2020-11-26
@TechnicalMan94

array_multisort(
    array_column($array, 'unread_pm'), SORT_DESC, 
    array_column($array, 'last_date'), SORT_DESC, 
    $array
);

If you are making a selection from the database, then sorting can be done in a SQL query
SELECT ... ORDER BY unread_pm DESC, last_date DESC

R
Rsa97, 2020-11-26
@Rsa97

usort + a function that specifies a greater/less than/equal relationship between two elements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question