array_multisort()
是 PHP 中的一个内置函数,用于对多个数组或多维数组进行排序
以下是 array_multisort()
函数在 PHP 中的一些应用技巧:
$array1 = array("apple", "orange", "banana", "pear");
$array2 = array(4, 2, 3, 1);
array_multisort($array2, SORT_ASC, $array1);
print_r($array1); // Output: Array ( [0] => pear [1] => orange [2] => banana [3] => apple )
print_r($array2); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
$array = array(
"one" => 1,
"three" => 3,
"two" => 2,
"four" => 4
);
array_multisort(array_keys($array), SORT_ASC, $array);
print_r($array); // Output: Array ( [four] => 4 [one] => 1 [three] => 3 [two] => 2 )
function custom_sort($a, $b) {
return strlen($a) - strlen($b);
}
$array = array("apple", "banana", "kiwi", "grape");
usort($array, "custom_sort");
print_r($array); // Output: Array ( [0] => kiwi [1] => apple [2] => grape [3] => banana )
$array = array(
array("name" => "John", "age" => 25),
array("name" => "Jane", "age" => 30),
array("name" => "Mike", "age" => 28)
);
array_multisort(array_column($array, 'age'), SORT_ASC, $array);
print_r($array); // Output: Array ( [0] => Array ( [name] => John [age] => 25 ) [1] => Array ( [name] => Mike [age] => 28 ) [2] => Array ( [name] => Jane [age] => 30 ) )
这些示例展示了如何在 PHP 中使用 array_multisort()
函数对多个数组、多维数组和自定义排序规则进行排序。通过熟练掌握这些技巧,您可以更有效地处理数组数据。