I
I
Ivan Vekov2017-05-10 15:04:58
PHP
Ivan Vekov, 2017-05-10 15:04:58

How to sort an array by the values ​​of multiple keys?

There is an array of objects. Let's say for a residential building:

[1] => array( 'Тип' => 'Квартира', "Номер объекта" => '4', 'ID' => '333'),
[2] => array( 'Тип' => 'Квартира', "Номер объекта" => '7', 'ID' => '444'),
[3] => array( 'Тип' => 'Машиноместо', "Номер объекта" => '3', 'ID' => '555' ),
[4] => array( 'Тип' => 'Машиноместо', "Номер объекта" => '2', 'ID' => '777' ),
[5] => array( 'Тип' => 'Квартира', "Номер объекта" => '2', 'ID' => '888'),

How to sort this array so that first there are elements of one type, then another, and at the same time go in ascending order by the value of "Object numbers"?
That is, to line up like this:
[5] => array( 'Тип' => 'Квартира', "Номер объекта" => '2', 'ID' => '888'),
[1] => array( 'Тип' => 'Квартира', "Номер объекта" => '4', 'ID' => '333'),
[2] => array( 'Тип' => 'Квартира', "Номер объекта" => '7', 'ID' => '444'),
[4] => array( 'Тип' => 'Машиноместо', "Номер объекта" => '2', 'ID' => '777' ),
[3] => array( 'Тип' => 'Машиноместо', "Номер объекта" => '3', 'ID' => '555' ),

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Vekov, 2017-05-10
@vekov

Thanks for the multisort link, Vladislav Tishin .
Among the examples there I found the right solution:

function array_orderby()
{
  $args = func_get_args();
  $data = array_shift($args);
  foreach ($args as $n => $field) {
    if (is_string($field)) {
      $tmp = array();
      foreach ($data as $key => $row)
        $tmp[$key] = $row[$field];
        $args[$n] = $tmp;
    }
  }
  $args[] = &$data;
  call_user_func_array('array_multisort', $args);
  return array_pop($args);
}

$arObjects = array_orderby($arObjects, 'Тип', SORT_ASC, 'Номер объекта', SORT_ASC);

V
Vlad, 2017-05-10
@vladgba

usort
php.net/manual/ru/function.usort.php
array_multisort
php.net/manual/ru/function.array-multisort.php

O
Oleg, 2017-05-10
@Austin_Powers

If this array is the result of a query to the database, then it is better to sort in the sql query using order by

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question