php sort function array_mulitsort

1. Concept
The array_multisort() function sorts multiple arrays or multidimensional arrays.
The array in the parameter is treated as a table column and sorted by row - this is similar to how SQL's ORDER BY clause functions. The first array is the main array to be sorted. Rows (values) in an array that compare equal are sorted by the size of the corresponding value in the next input array, and so on.
The first argument is an array, each subsequent argument may be an array, or one of the following sort order flags (sort flags are used to change the default sort order):
SORT_ASC - Default, ascending order. (AZ)
SORT_DESC - Sort in descending order. (ZA)
2. Examples

Please reorder the two-dimensional array according to the length of name, and assign id values ​​in order (starting from 1).

array is

$arr = array(
    array('id'=>0,'name'=>"aaaaaaaaa"),
    array('id'=>0,'name'=>"1212121"),
    array('id'=>0,'name'=>"acdd"),
    array('id'=>0,'name'=>"123"),
    array('id'=>0,'name'=>"1"),
    array('id'=>0,'name'=>"fdsafdsafdsafd"),
    array('id'=>0,'name'=>"dddddddddd")
);

The source code is as follows

$arr = array(
    array('id'=>0,'name'=>"aaaaaaaaa"),
    array('id'=>0,'name'=>"1212121"),
    array('id'=>0,'name'=>"acdd"),
    array('id'=>0,'name'=>"123"),
    array('id'=>0,'name'=>"1"),
    array('id'=>0,'name'=>"fdsafdsafdsafd"),
    array('id'=>0,'name'=>"dddddddddd")
);
//Newly define an array to store the length of the name in the array to be sorted
foreach ($arr as $item) {
    $arr2[] = strlen($item['name']);
}
// sort by the length of the name
array_multisort($arr2,$arr);
//Reassign the id
foreach ($arr as $k=>$v) {
    $arr[$k]["id"] = $k+1;
}
// formatted output
echo "<pre>";
var_dump($arr);
echo "</pre>";




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325938994&siteId=291194637