05c04-1.php
来自「介绍PHP5的给类型函数应用」· PHP 代码 · 共 60 行
PHP
60 行
<?php// Create a nested array structure$scores = array ( 'Siegfried' => array(117, 72, 53.3), 'Francesca' => array(84.7), 'Jonathas' => array(96.7, 37), 'Mika' => array(113, 100, 81), 'Timothy' => array(80.7, 80.3), );// Create a function that will sort based upon the length of the subarrayfunction compare_length($a, $b) { // For each look at the length of the subarray $a_length = count($a); $b_length = count($b); // If they are the same, return 0 if ($a_length == $b_length) { return 0; } else { // See which one is bigger return ($a_length > $b_length) ? -1 : 1; }}// Using that formula, sort the array, keeping the key associations intact:uasort($scores, 'compare_length');// Echo out the keys in their new order ... Will be in order:// Mika, Siegfried, Timothy, Jonathas, Francescaecho '<pre>';echo "Sorted by array length: \n";print_r(array_keys($scores));echo "\n\n";// Create a function to sort them by the maximum value in the subarrayfunction compare_max($a, $b) { // Take a look a the maximum values: $a_max = max($a); $b_max = max($b); // If they are the same, return 0 if ($a_max == $b_max) { return 0; } else { // See which one is bigger return ($a_max > $b_max) ? -1 : 1; }}// Resort the array by maximum value:uasort($scores, 'compare_max');// Echo out the keys now sorted by max ... Will be in order:// Siegfried, Mika, Jonathas, Francesca, Timothyecho "Sorted by array maximum value: \n";print_r(array_keys($scores));echo '</pre>';?>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?