Home  >  Article  >  PHP commonly used array functions (4)

PHP commonly used array functions (4)

无忌哥哥
无忌哥哥Original
2018-06-28 10:34:231825browse

* Array sorting

* Note:

* 1. Arrays are passed by reference, and all original data will be overwritten;

* 2. Array elements It is recommended that all types be the same, otherwise unpredictable results will occur

* 3. Sorting success returns: true, failure returns: false

* Available constants:

* 1.SORT_REGULAR : [Default] Normally compare units (do not change type)

* 2.SORT_NUMERIC: Units are compared as numbers

* 3.SORT_STRING: Units are compared as strings

* 4.SORT_NATURAL: The unit sorts strings in "natural order"

* 5.SORT_FLAG_CASE: Sorts strings case-insensitively

* 1. Positive order: associate (associated), key (key), preceded by the first letters of these two words means

* 1. sort(&$arr, $flag) Arrange in ascending order by value, key name according to index Reset

* 2. asort(&$arr,$flag) Sort by value in ascending order, key name retains correspondence with value

* 3. ksort(&$arr,$flag) Sort by key name in ascending order, suitable for associative arrays, the key-value correspondence remains unchanged

* 2. Reverse order: reversal, just add an r before the function

* 1. rsort( &$arr, $flag): Reverse sort the array

* 2. arsort(&$arr, $flag): Reverse sort the array and maintain the index relationship

* 3. krsort (&$arr, $flag): Sort the array in reverse order by key name

* 3. Customize the callback function to sort: usort(&$arr, functoin($a, $b){ #code } )

* Note: Only sort the values, ignore the key name (that is, the key name will be reset)

$arr = ['id'=>3, 'name'=>'zhu', 'course'=>'php', 'grade'=>60, 5=>true];
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
echo &#39;<p>原始数组:</p>&#39;;
print_r($arr);
echo &#39;<hr color="red">&#39;;

//Here is a very simple example, more complex cases will Introduced in actual combat

$arr1 = [10, 4, 22, 99, 35, 18];

//Now we use the custom callback method to arrange $arr1 from small to large

usort($arr1, function($a, $b) {
$res = $a - $b; 
if ($res == 0) {
return 0;
} else if ($res > 0) {
return true;
} else {
return false;
}
});
print_r($arr1);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn