arsort()
是 PHP 中的一个内置函数,用于对数组进行降序排序
$users = [
['name' => 'Alice', 'created_at' => 1609459200],
['name' => 'Bob', 'created_at' => 1609372800],
['name' => 'Charlie', 'created_at' => 1609545600],
];
arsort($users);
foreach ($users as $user) {
echo $user['name'] . ' - ' . $user['created_at'] . PHP_EOL;
}
输出结果:
Charlie - 1609545600
Alice - 1609459200
Bob - 1609372800
$cart = [
['product_id' => 1, 'price' => 100],
['product_id' => 2, 'price' => 50],
['product_id' => 3, 'price' => 200],
];
arsort($cart);
foreach ($cart as $item) {
echo 'Product ID: ' . $item['product_id'] . ', Price: ' . $item['price'] . PHP_EOL;
}
输出结果:
Product ID: 2, Price: 50
Product ID: 1, Price: 100
Product ID: 3, Price: 200
arsort()
可以用于根据分数或其他指标对用户进行排序。$scores = [
['user_id' => 1, 'score' => 100],
['user_id' => 2, 'score' => 200],
['user_id' => 3, 'score' => 150],
];
arsort($scores);
foreach ($scores as $entry) {
echo 'User ID: ' . $entry['user_id'] . ', Score: ' . $entry['score'] . PHP_EOL;
}
输出结果:
User ID: 2, Score: 200
User ID: 3, Score: 150
User ID: 1, Score: 100
这些示例展示了 arsort()
在实际应用中的一些常见用途。当然,这个函数可以根据需要用于其他场景,只需根据具体需求调整排序依据即可。