Home  >  Article  >  Backend Development  >  How to sort a two-dimensional array by a certain key in PHP

How to sort a two-dimensional array by a certain key in PHP

墨辰丷
墨辰丷Original
2018-06-01 11:15:211381browse

This article mainly introduces the method of sorting a certain key of a two-dimensional array in PHP, involving PHP's operation skills for array traversal, comparison, sorting and other related operations. Friends in need can refer to the following

for details As follows:

/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param string $sortby 排序类型 (asc正向排序 desc逆向排序 nat自然排序)
 * @return array
 */
  function list_sort_by($list, $field, $sortby = 'asc')
  {
    if (is_array($list))
    {
      $refer = $resultSet = array();
      foreach ($list as $i => $data)
      {
        $refer[$i] = &$data[$field];
      }
      switch ($sortby)
      {
        case 'asc': // 正向排序
          asort($refer);
          break;
        case 'desc': // 逆向排序
          arsort($refer);
          break;
        case 'nat': // 自然排序
          natcasesort($refer);
          break;
      }
      foreach ($refer as $key => $val)
      {
        $resultSet[] = &$list[$key];
      }
      return $resultSet;
    }
    return false;
  }
/**
 * 例子
 * 求:根据二维数组的id键值降序排列(也就是id越大的排在越前)?
 */
$list = array(
  0 => array(
    'id' => 1,
    'name' => '第一'
  ),
  1 => array(
    'id' => 3,
    'name' => '第三'
  ),
  2 => array(
    'id' => 2,
    'name' => '第二'
  ),
  3 => array(
    'id' => 4,
    'name' => '第四'
  ),
);
//解答
$new_list = list_sort_by($list, 'id', 'desc');
print_r($new_list);

The running results are as follows:

Array
(
  [0] => Array
    (
      [id] => 4
      [name] => 第四
    )
  [1] => Array
    (
      [id] => 3
      [name] => 第三
    )
  [2] => Array
    (
      [id] => 2
      [name] => 第二
    )
  [3] => Array
    (
      [id] => 1
      [name] => 第一
    )
)

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

Related recommendations:

phpAchieve adding a circular logo icon to the background image

PHP Implemented custom array sorting function and sorting class methods

Customized array sorting function and sorting class implemented in PHP

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

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