C
C
CrewCut2015-08-27 13:49:23
PHP
CrewCut, 2015-08-27 13:49:23

How to set up sorting like 1-2-10-11 for an array in PHP?

I have an array like this:

Array (
  [import_files/5d/namers.jpg] => Array ([description] => 1 колечко блестящее),
  [import_files/5d/name31.jpg] => Array ([description] => 10 морозное утро),
  [import_files/5d/name13.jpg] => Array ([description] => 4 морозное утро),
  [import_files/5d/name2.jpg] => Array ([description] => 8 колечко матовое)
  [import_files/5d/name12.jpg] => Array ([description] => 12 морозное утро),
  [import_files/5d/name14.jpg] => Array ([description] => 5 леопард),
)

I need to sort it keeping the key-value relation by value alphabetically. I use it for this asort();- but it sorts not quite correctly, the output is sorted like this (I indicate only the first digits):
  • one
  • ten
  • 12
  • 4
  • 5
  • eight

I'd like to get one like this:
  • one
  • 4
  • 5
  • eight
  • ten
  • 12

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaliy Orlov, 2015-08-27
@CrewCut

php.net/manual/en/function.uasort.php

$array = uasort($array, function(a, b){

тут надо сравнить буквы (если по алфавиту) 
из a['description'] с b['description']
и вернуть в $res -1, 0 или 1 соответственно

return $res;

});

print_r($array);

N
Nazar Mokrinsky, 2015-08-27
@nazarpc

OK, Google...
https://secure.php.net/manual/en/function.natsort.php

A
Andrey Burov, 2015-08-27
@BuriK666

asort($arr, SORT_NUMERIC);
UPD: works for me

$arr = [
    'a' => '1 a',
    'b' => '10 b',
    'c' => '4 c',
    'd' => '8 d',
    'e' => '12 e',
    'f' => '5 f'
];

asort($arr);
var_dump($arr);

asort($arr, SORT_NUMERIC);
var_dump($arr);

array(6) {
  'a' =>
  string(3) "1 a"
  'b' =>
  string(4) "10 b"
  'e' =>
  string(4) "12 e"
  'c' =>
  string(3) "4 c"
  'f' =>
  string(3) "5 f"
  'd' =>
  string(3) "8 d"
}
array(6) {
  'a' =>
  string(3) "1 a"
  'c' =>
  string(3) "4 c"
  'f' =>
  string(3) "5 f"
  'd' =>
  string(3) "8 d"
  'b' =>
  string(4) "10 b"
  'e' =>
  string(4) "12 e"
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question