Y
Y
Yuri Pikhtarev2012-09-05 12:56:51
PHP
Yuri Pikhtarev, 2012-09-05 12:56:51

Sorting nested arrays

Good day.

Tell me please. I have an array like this:

Array (
  [1] => Array ( [name] => Бананы [count] => 16 )
  [2] => Array ( [name] => Груши [count] => 12 )
  [3] => Array ( [name] => Яблоки [count] => 1 )
  [4] => Array ( [name] => Апельсины [count] => 1 )
  [5] => Array ( [name] => Мандарины [count] => 5 )
)

You need to sort the nested arrays in ascending order of their count key, so that you get something like this:

Array (
  [4] => Array ( [name] => Апельсины [count] => 1 )
  [3] => Array ( [name] => Яблоки [count] => 1 )
  [5] => Array ( [name] => Мандарины [count] => 5 )
  [2] => Array ( [name] => Груши [count] => 12 )
  [1] => Array ( [name] => Бананы [count] => 16 )
)

The standard php functions for arrays are not suitable - the array is multidimensional, and multisort does not sort the nested arrays themselves, it can only be used to sort their values. I would be grateful for possible solutions to this problem.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
G
gaelpa, 2012-09-05
@gaelpa

5.3+

uksort($arr,function($a,$b){ return $b['count'] - $a['count'];})

5.2 - the same, but take out the function separately.

D
DarthRamone, 2012-09-05
@DarthRamone

I do not really understand. How about writing a quicksort yourself?

E
Evgeny Borisov, 2012-09-05
@Agel_Nash

Do you say the standard functions do not fit? multisort can't? Or maybe I misunderstood the task, but the result is the same: pastebin.com/L03vF8SX

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question