Home  >  Article  >  Backend Development  >  php multidimensional array sorting

php multidimensional array sorting

WBOY
WBOYOriginal
2016-07-30 13:30:281117browse

Custom function multi-dimensional array sorting:

Function:

	/**
	* @param array $list 要排序的数组
	* @param string $sort_key  要按照排序的字段
	* @param $order 排序方式,省略默认降序  降序SORT_DESC   升序  SORT_ASC
	* @return array 返回排序后的数组
	*/
	function getSort($list,$sort_key,$order=SORT_DESC){
		if(!is_array($list)){
			return $list;
		}
		$key_array = array();
		foreach($list as $v){
			$key_array[] = $v[$sort_key];
		}
		array_multisort($key_array,$order,$list);
		return $list;
	}

Usage:

<?php
    header(&#39;Content-type:text/html;charset=utf-8&#39;);
    $list = array(
&#160;&#160; &#160;    array(&#39;name&#39;=>'张三','age'=>111,'grade'=>'60'),
        array('name'=>'李四','age'=>12,'grade'=>'80'),
        array('name'=>'王五','age'=>21,'grade'=>'50'),
        array('name'=>'王五','age'=>3,'grade'=>'50'),
    );
    $list = getSort($list,'age',SORT_ASC);
    var_dump($list);
?>


Output result:


Copyright statement: This article is an original article by the blogger and may not be used without the blogger's permission. Reprint.

The above introduces PHP multi-dimensional array sorting, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

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