Home > Backend Development > PHP Tutorial > PHP二维数组排序简单实现方法_PHP

PHP二维数组排序简单实现方法_PHP

WBOY
Release: 2016-05-28 11:48:38
Original
950 people have browsed it

本文实例讲述了PHP二维数组排序简单实现方法。分享给大家供大家参考,具体如下:

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 == 'desc')&#63;-1:1) * (($a[$key] < $b[$key]) &#63; -1 : 1);
  }
  return 0;
}
$arr = array(
  array('gold'=>1, 'silver'=>2),
  array('gold'=>8, 'silver'=>10),
  array('gold'=>8, 'silver'=>8),
  array('gold'=>2, 'silver'=>1),
);
uasort($arr, 'multi_compare');
print_r($arr);

Copy after login

运行结果如下:

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

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php排序算法总结》、《PHP基本语法入门教程》、《PHP错误与异常处理方法总结》及《php常用函数与技巧总结》

希望本文所述对大家PHP程序设计有所帮助。

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