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()
函數對多個數組、多維數組和自定義排序規則進行排序。通過熟練掌握這些技巧,您可以更有效地處理數組數據。