L
L
lostinvlg2016-06-16 16:01:56
PHP
lostinvlg, 2016-06-16 16:01:56

Sorting nested multidimensional arrays?

Good afternoon! There is an array like:

$books = array(
  array(
    "book" => "От простого сложного",
    "autor" => "Иванов А.А.",
    "prices" => array(
      array(
        "price" => 354
      ),
      array(
        "price" => 294
      ),
      array(
        "price" => 280
      )
    )
  ),
  array(
    "brand" => "Наука и мир",
    "autor" => "Петров С.А.",
    "prices" => array(
      array(
        "price" => 798
      ),
      array(
        "price" => 657
      ),
      array(
        "price" => 812
      )
    )
  )
);

It is necessary to perform sorting by authors, and also for each, sorting by prices.
There are no problems with sorting by author, array_multisort (just like usort) does a great job with this. But how to sort arrays by price?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lostinvlg, 2016-06-16
@lostinvlg

Made a working version:

// Порядок сортировки
$sort_type_autor = 'ASC';
$sort_type_price = 'ASC';

for($i = 0; $i<count($books); $i++) {
  // Массив ключ-значение для array_multisort
  $sort_autor[$i] = $books[$i]['autor'];
  // Сортируем по ценам в каждом товаре
  foreach($books[$i]['prices'] as $k=>$v) {
    switch($sort_type_price) {
      case 'DESC':
        arsort($books[$i]['prices']);
        break;
      case 'ASC':
        asort($books[$i]['prices']);
        break;
    }
  }
}

// Сортируем по авторам
switch($sort_type_autor) {
  case 'DESC':
    array_multisort($sort_autor, SORT_DESC, $books);
    break;
  case 'ASC':
    array_multisort($sort_autor, SORT_ASC, $books);
    break;
}

Perhaps there is a more "elegant" solution?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question