Home > Backend Development > PHP Tutorial > PHP multidimensional array sorting problem Sorting based on an item in a two-dimensional array_PHP tutorial

PHP multidimensional array sorting problem Sorting based on an item in a two-dimensional array_PHP tutorial

WBOY
Release: 2016-07-21 15:22:57
Original
958 people have browsed it

PHP built-in function array_multisort requires that each array is of the same size
$areas is a two-dimensional array of areas, including the number of people and times. Now we need to sort these two numbers in descending order

Copy Code The code is as follows:

foreach($areaArray as &$areas) {
$times = $numbers = array();
foreach($areas as $province => $v) {
$times[$province] = $v['times'];
$numbers[$province] = $v['numbers'];
}
array_multisort($times, SORT_DESC, $numbers, SORT_DESC, $areas);
}

For example, there is a multisort array:
Copy the code The code is as follows:

$arr = array(
'd' => array('id' => 5, 'name' => 1, 'age' => 7),
'b' => array('id' => 2,'name' => 3,'age' => 4),
'a' => array('id' => 8,'name' => 10,'age' => 5),
'c' => array('id' => 1,'name' => 2,'age' => 2)
);

Need to sort the age items in the two-dimensional array.
You need to use PHP’s built-in function array_multisort(), you can read the manual.
Custom function:
Copy code The code is as follows:

function multi_array_sort($multi_array,$sort_key,$sort =SORT_ASC){
if(is_array($multi_array)){
foreach ($multi_array as $row_array){
if(is_array($row_array)){
$key_array[] = $row_array [$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_array,$ sort,$multi_array);
return $multi_array;
}
//processing
echo “
”; 
print_r(multi_array_sort($arr,'age') );exit;
//Output
Array
(
[c] => Array
(
[id] => 1
[name] => ; 2
[age] => 2
)
[b] => Array
(
[id] => 2
[name] => 3
[age] => 4
)
[a] => Array
(
[id] => 8
[name] => 10
[age] => 5
)
[d] => Array
(
[id] => 5
[name] => 1
[ age] => 7
)
)
written by Daewoo
0

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324592.htmlTechArticlePHP built-in function array_multisort requires each array to be the same size. $areas is a two-dimensional array of areas, including the number of people and times. Now we need to sort these two numbers in descending order. Copy the code. The code is as follows...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template