# 3.2. 数组排序 4 4

## sort()

``````\$products = ['tires', 'oil', 'spark'];
sort(\$products);``````

``````\$prices = [100, 10, 4];
sort(\$prices);``````

``````\$arr = ['a', 'B', 'c', 'D'];

sort(\$arr);

print_r(\$arr);
/* Array
(
[0] => B
[1] => D
[2] => a
[3] => c
) */``````

• SORT_REGULAR (默认) 正常比较单元
• SORT_NUMERIC 单元被作为数字来比较
• SORT_STRING 单元被作为字符串来比较
比如，比较数值 `2`，和字符串`'12'`, 数字是 `2 < 12`, 按字符串来说 `'12' < '2'`

## asort()

``````\$arr = ['tires' => 100, 'oil' => 10, 'spark' => 4];

asort(\$arr);

print_r(\$arr);
/* Array
(
[spark] => 4
[oil] => 10
[tires] => 100
) */``````

## ksort()

``````\$arr = ['tires' => 100, 'oil' => 10, 'spark' => 4];

ksort(\$arr);

print_r(\$arr);
/* Array
(
[oil] => 10
[spark] => 4
[tires] => 100
) */``````

## 多维数组排序

``````\$products = [
['TIR', 'Tires', 100],
['OIL', 'Oil', 10],
['SPK', 'Spark Plugs', 4]
];``````

``````function compare(\$x, \$y) {
if(\$x[1] == \$y[1]) {
return 0;
} else if (\$x[1] < \$y[1]) {
return -1;
} else {
return 1;
}
}

usort(\$products, 'compare');``````

``````function compare(\$x, \$y) {
if(\$x[2] == \$y[2]) {
return 0;
} else if(\$x[2] < \$y[2]) {
return -1;
} else {
return 1;
}
}

usort(\$products, 'compare');``````

• sort() — usort()
• asort() — uasort()
• ksort() — uksort()

``````\$products = [
['TIR', 'Tires', 100],
['OIL', 'Oil', 10],
['SPK', 'Spark Plugs', 4]
];

function reverse_compare(\$x, \$y) {
if(\$x[2] == \$y[2]) {
return 0;
} elseif(\$x[2] < \$y[2]) {
return 1; // 哪个在前面，就返回1
} else {
return -1;
}
}

usort(\$products, 'reverse_compare');

print_r(\$products);``````

## shuffle() 随机打乱数组元素的排序

``````\$pictures = ['tire.jpg', 'oil.jpg', 'spark_plug.jpg', 'door.jpg', 'steering_wheel.jpg', 'thermostat.jpg'];

shuffle(\$pictures);

print_r(\$pictures);``````

## array_reverse()

1. for, array_push
``````\$numbers = [];
for(\$i=10; \$i > 0; \$i--) {
array_push(\$numbers, \$i); // 与之相反的函数array_pop()
}``````
2. range(), rsort()
``````\$numbers = range(1, 10);
rsort(\$numbers);``````
3. range(), array_reverse()
``````\$numbers = range(1, 10);
\$numbers = array_reverse(\$numbers);``````
4. range()
``````\$numbers = range(10, 1, -1);
\$numbers = range(10, 1); // 不加-1也是可以的``````