На странице произошла ошибка #S51. Свяжитесь с вебмастером. PHP 5.6 и PHP 7 на русском: Функция usort() - Сортирует массив по значениям используя пользовательскую функцию для сравнения элементов

usort

(PHP 4, PHP 5, PHP 7)

usortСортирует массив по значениям используя пользовательскую функцию для сравнения элементов

Описание

bool usort ( array &$array , callable $value_compare_func )

Эта функция сортирует элементы массива, используя для сравнения значений callback-функцию, предоставленную пользователем. Используйте эту функцию, если вам нужно отсортировать массив по какому-нибудь необычному признаку.

Замечание:

Если два элемента исходного массива равны, их порядок относительно друг друга в отсортированном массиве не определён.

Замечание: Эта функция присваивает новые ключи элементам массива. Она удалит все существующие ключи, а не просто переупорядочит их.

Список параметров

array

Входной массив.

value_compare_func

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим чем второй.

int callback ( mixed $a, mixed $b )
Предостережение

Возвращаемые нецелочисленные (non-integer) значения из функции сравнения, такие как float, будут приводиться к типу integer. Поэтому такие значения, как 0.99 и 0.1, будут приводиться к целому числу 0, что указывает на равенство сравниваемых значений.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия Описание
4.1.0 Представлен новый алгоритм сортировки. Функция value_compare_func не сохраняет исходный порядок одинаковых элементов.

Примеры

Пример #1 Пример использования usort()

<?php
function cmp($a$b)
{
    if (
$a == $b) {
        return 
0;
    }
    return (
$a $b) ? -1;
}

$a = array(32561);

usort($a"cmp");

foreach (
$a as $key => $value) {
    echo 
"$key$value\n";
}
?>

Результат выполнения данного примера:

0: 1
1: 2
2: 3
3: 5
4: 6

Замечание:

Очевидно, что для этого тривиального случая более подходит функция sort().

Пример #2 Пример использования функции usort() с многомерными массивами

<?php
function cmp($a$b)
{
    return 
strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits"cmp");

while (list(
$key$value) = each($fruits)) {
    echo 
"\$fruits[$key]: " $value["fruit"] . "\n";
}
?>

При сортировке многомерного массива переменные $a и $b содержат ссылки на первые два индекса массива.

Результат выполнения данного примера:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

Пример #3 Пример использования usort() с методом класса

<?php
class TestObj {
    var 
$name;

    function 
TestObj($name)
    {
        
$this->name $name;
    }

    
/* Это статическая функция сравнения: */
    
static function cmp_obj($a$b)
    {
        
$al strtolower($a->name);
        
$bl strtolower($b->name);
        if (
$al == $bl) {
            return 
0;
        }
        return (
$al $bl) ? +: -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

usort($a, array("TestObj""cmp_obj"));

foreach (
$a as $item) {
    echo 
$item->name "\n";
}
?>

Результат выполнения данного примера:

b
c
d

Пример #4 Пример использования функции usort() с применением анонимной функции для сортировки многомерного массива

<?php
$array
[0] = array('key_a' => 'z''key_b' => 'c');
$array[1] = array('key_a' => 'x''key_b' => 'b');
$array[2] = array('key_a' => 'y''key_b' => 'a');

function 
build_sorter($key) {
    return function (
$a$b) use ($key) {
        return 
strnatcmp($a[$key], $b[$key]);
    };
}

usort($arraybuild_sorter('key_b'));

foreach (
$array as $item) {
    echo 
$item['key_a'] . ', ' $item['key_b'] . "\n";
}
?>

Результат выполнения данного примера:

y, a
x, b
z, c

Смотрите также

Коментарии

Needed a date sort and I didn't know if one was available so I wrote one. Maybe it'll help someone:

<?php
function DateSort($a,$b,$d="-") {
    if (
$a == $b) {
        return 
0;
    } else { 
//Convert into dates and compare
       
list($am,$ad,$ay)=split($d,$a);
        list(
$bm,$bd,$by)=split($d,$b);
        if (
mktime(0,0,0,$am,$ad,$ay) < mktime(0,0,0,$bm,$bd,$by)) {
            return -
1;
        } else {
            return 
1;
        }
    }
}
?>

$d is the delimeter
2000-09-19 02:35:38
http://php5.kiev.ua/manual/ru/function.usort.html
when using usort to refer to a function inside a class i have succesfully used:

<?php usort($myarray,array($this,"cmp")); ?>
2001-03-20 07:16:09
http://php5.kiev.ua/manual/ru/function.usort.html
If you want to sort an array according to another array acting as a priority list, you can use this function.

<?php
function listcmp($a$b)
{
  global 
$order;

  foreach(
$order as $key => $value)
    {
      if(
$a==$value)
        {
          return 
0;
          break;
        }

      if(
$b==$value)
        {
          return 
1;
          break;
        }
    }
}

$order[0] = "first";
$order[1] = "second";
$order[2] = "third";

$array[0] = "second";
$array[1] = "first";
$array[2] = "third";
$array[3] = "fourth";
$array[4] = "second";
$array[5] = "first";
$array[6] = "second";

usort($array"listcmp");

print_r($array);
?>
2002-09-20 12:29:51
http://php5.kiev.ua/manual/ru/function.usort.html
Instead of doing  :

<?php $strc strcmpstrtolower($a[$f]), strtolower($b[$f]) ); ?>

you could do this : 

<?php $strc strcasecmp$a[$f], $b[$f] ); ?>

which is more efficient and is does case insensitive comparison according to the current locale.
2006-01-16 03:44:54
http://php5.kiev.ua/manual/ru/function.usort.html
If you need to use usort with a key in the calling method, I wrote this as a utility:
<?php

function usort_comparison($obj$method$key) {
   
$usorter = &new Usort($obj$method$key);
    return array(
$usorter"sort");
}

class 
Usort {
    function 
__construct($obj$method$key) {
       
$this->obj $obj;
       
$this->method $method;
       
$this->key $key;
    }
    function 
sort($a$b) {
        return 
call_user_func_array(array($this->obj$this->method), array($a$b$this->key));
    }
}

?>

<?php

require_once("util/usort.php");

class 
Foo {
   
$items = array(FooBar(13), FooBar(2));
    public function 
sorter() {
       
usort($this-itemsusort_comparison("Foo""_cmp""item"));
    }

    public static function 
_cmp($a$b$key) {
         return 
strcasecmp($a->$key$b->$key);
    }

}

class 
FooBar {
    public 
$item;
    function 
__construct($val) {
       
$this->item $val;
    }
}

?>

~ simple example... but in the way I need to use it was the key was used in a switch statement to choose the different member of the object to compare against dynamically (as in, sort by x or y or z)
2009-03-28 14:25:32
http://php5.kiev.ua/manual/ru/function.usort.html
I needed a sort method that would sort strings but take note of any numbers and would compare them as number. I also want to ignore any non alphanumerical characters.

Eg.
Slot 1 Example
Slot 10 Example
Slot 2 Example

Should infact be
Slot 1 Example
Slot 2 Example
Slot 10 Example

<?php
function sort_with_numbers($a $b) {
   
$a explode(' ',$a);
   
$b explode(' ',$b);
   
$size min(count($a), count($b));
    for(
$index =0$index $size; ++$index) {
       
$a1 ereg_replace("[^A-Za-z0-9]""",$a[$index]);
       
$b1 ereg_replace("[^A-Za-z0-9]""",$b[$index]);
       
$equal 0;
        if (
is_numeric($a1) && is_numeric($b1)) {
           
$equal $a1 $b1;
        } else {
           
$equal strcasecmp($a1,$b1);
        }
        if (
$equal 0) {
            return -
1;
        }
        if (
$equal 0) {
            return 
1;
        }
    }
    return 
count($a) - count($b);   
}
?>
2012-02-04 17:58:08
http://php5.kiev.ua/manual/ru/function.usort.html
Автор:
As the documentation says, the comparison function needs to return an integer that is either "less than, equal to, or greater than zero". There is no requirement to restrict the value returned to -1, 0, 1.

<?php
usort
($array, function($a$b) {
    if(
$a->integer_property $b->integer_property) {
        return 
1;
    }
    elseif(
$a->integer_property $b->integer_property) {
        return -
1;
    }
    else {
        return 
0;
    }
});
?>

can be simplified to

<?php
usort
($array, function($a$b) {
    return 
$a->integer_property $b->integer_property;
});
?>

This of course applies to any comparison function that calculates an integer "score" for each of its arguments to decide which is "greater".
2013-04-09 01:30:19
http://php5.kiev.ua/manual/ru/function.usort.html
to sort with numeric and empty values  and have the smallest on top:
<?php
    usort
($list, function($a$b) {
        if( 
$a == null && $b != null ) return 1;
        if( 
$a != null && $b == null ) return -1;
        return 
$a $b : -1;
    });
?>
returns
1
2
3
null
null
null
2017-01-14 20:51:17
http://php5.kiev.ua/manual/ru/function.usort.html
In case anyone is interested, comparative timings over 100000000 runs
Based on comparing integers (500 and 501)
Spaceship:4
()?: operator:10
Subtraction:2

Based on comparing floats (500.1 and 501.3) (caveats noted)
Spaceship:5
()?: operator:9
Subtraction:3

Based on comparing strings ("five" and "four")
Spaceship:7
()?: operator:17
(Subtraction obviously not available)

Note: a dummy run was done with an empty loop and the elapsed time for this was subtracted from each of the above times so that they reflect ONLY the time to do the comparisons. As for significance. unless you are doing very large numbers of comparisons where spaceships are the order of the day, the difference is insignificant.
2019-01-19 03:15:25
http://php5.kiev.ua/manual/ru/function.usort.html
This is a simple way to sort based on a "priority list":

<?php

$order 
= [1,3,0,2];
$arr =   [
    [ 
'id' => ],
    [ 
'id' => ],
    [ 
'id' => ],
    [ 
'id' => ],
];

uasort(
   
$arr
    function (
$a$b) use ($order) {
        return 
array_search($a['id'], $order) <=> array_search($b['id'], $order); 
    }
);

print_r($arr);

?>

This will return:

Array
(
    [1] => Array
        (
            [id] => 1
        )

    [3] => Array
        (
            [id] => 3
        )

    [0] => Array
        (
            [id] => 0
        )

    [2] => Array
        (
            [id] => 2
        )

)

Note that if you have a value in $arr that is not on the $order list, you will need additional checks since the array_search function returns FALSE for undefined indexes.
2019-06-10 16:23:06
http://php5.kiev.ua/manual/ru/function.usort.html

    Поддержать сайт на родительском проекте КГБ