Home > Backend Development > PHP Tutorial > How to sort two-dimensional array in PHP

How to sort two-dimensional array in PHP

墨辰丷
Release: 2023-03-29 18:34:01
Original
1849 people have browsed it

This article mainly introduces the method of sorting two-dimensional arrays in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

The code is as follows:

function multi_compare($a, $b)
{
  $val_arr = array(
      'gold'=>'asc',
      'silver'=>'desc'//还可以增加额外的排序条件
  );
  foreach($val_arr as $key => $val){
    if($a[$key] == $b[$key]){
      continue;
    }
    return (($val == &#39;desc&#39;)?-1:1) * (($a[$key] < $b[$key]) ? -1 : 1);
  }
  return 0;
}
$arr = array(
  array(&#39;gold&#39;=>1, &#39;silver&#39;=>2),
  array(&#39;gold&#39;=>8, &#39;silver&#39;=>10),
  array(&#39;gold&#39;=>8, &#39;silver&#39;=>8),
  array(&#39;gold&#39;=>2, &#39;silver&#39;=>1),
);
uasort($arr, &#39;multi_compare&#39;);
print_r($arr);
Copy after login

The running result is as follows:

Array
(
  [0] => Array
    (
      [gold] => 1
      [silver] => 2
    )
  [3] => Array
    (
      [gold] => 2
      [silver] => 1
    )
  [1] => Array
    (
      [gold] => 8
      [silver] => 10
    )
  [2] => Array
    (
      [gold] => 8
      [silver] => 8
    )
)
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php method to obtain the check box value and a simple example

php methods and examples to implement process control switch

php method of using text to count visits, graphic and text explanation

The above is the detailed content of How to sort two-dimensional array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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