Jump to content
  • Hello visitors, welcome to the Hacker World Forum!

    Red Team 1949  (formerly CHT Attack and Defense Team) In this rapidly changing Internet era, we maintain our original intention and create the best community to jointly exchange network technologies. You can obtain hacker attack and defense skills and knowledge in the forum, or you can join our Telegram communication group to discuss and communicate in real time. All kinds of advertisements are prohibited in the forum. Please register as a registered user to check our usage and privacy policy. Thank you for your cooperation.

    TheHackerWorld Official

PHP多维数组按照某个字段进行排序

 Share


Recommended Posts

作为开发人员,您可能会遇到这种情况,即数据库中有一个按特定顺序获取的数据列表,但您希望在前端显示这些项目时安装期中某一个字段进行排序。

比如数组:

$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);

你希望得到以下结果:

$mylist = array(
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting')
);

我们可以使用两种不同的方法来做到这一需求。

  1. PHP usort()函数
  2. PHP array_mulitsort()函数

 

PHP usort()实现多维数组按某一键值排序

如果您仍使用PHP 5.2或更早版本,则必须先定义一个排序函数

function sortByOrder($a, $b) {
    return $a['id'] - $b['id'];
}

usort($myArray, 'sortByOrder');

从PHP 5.3开始,您可以使用匿名函数:

usort($myArray, function($a, $b) {
    return $a['id'] - $b['id'];
});

在PHP 7中,您可以使用spaceship运算符:

usort($myArray, function($a, $b) {
    return $a['id'] <=> $b['id'];
});

如果要基于多个键值对数组进行排序,则必须在回调函数中编写一些复杂的逻辑。如:

usort($myArray, function($a, $b) {
    $retval = $a['id'] <=> $b['id'];
    if ($retval == 0) {
        $retval = $a['suborder'] <=> $b['suborder'];
        if ($retval == 0) {
            $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
        }
    }
    return $retval;
});

 

PHP array_mulitsort()实现多维数组排序

PHP array_multisort() 对多个数组或多维数组进行排序 

语法:

bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]] )

 如果成功则返回 TRUE,失败则返回 FALSE。 

array_multisort() 可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序。 

关联(string)键名保持不变,但数字键名会被重新索引。 

输入数组被当成一个表的列并以行来排序――这类似于 SQL 的 ORDER BY 子句的功能。第一个数组是要排序的主要数组。数组中的行(值)比较为相同的话就按照下一个输入数组中相应值的大小来排序,依此类推。 

本函数的参数结构有些不同寻常,但是非常灵活。第一个参数必须是一个数组。接下来的每个参数可以是数组或者是下面列出的排序标志。 

排序顺序标志: 

  • SORT_ASC – 按照上升顺序排序 
  • SORT_DESC – 按照下降顺序排序 

 

排序类型标志: 

  • SORT_REGULAR – 将项目按照通常方法比较 
  • SORT_NUMERIC – 将项目按照数值比较 
  • SORT_STRING – 将项目按照字符串比较 

每个数组之后不能指定两个同类的排序标志。每个数组后指定的排序标志仅对该数组有效 – 在此之前为默认值 SORT_ASC 和 SORT_REGULAR。 

示例:

$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);
$keys = array_column($mylist, 'id');
array_multisort($keys, SORT_ASC, $mylist);
var_dump($mylist);

结果:

array (
  0 => 
  array (
    'ID' => 4,
    'title' => 'Duct Tape Party',
    'event_type' => 'party',
  ),
  1 => 
  array (
    'ID' => 3,
    'title' => 'Mario Party',
    'event_type' => 'party',
  ),
  2 => 
  array (
    'ID' => 1,
    'title' => 'Boring Meeting',
    'event_type' => 'meeting',
  ),
  3 => 
  array (
    'ID' => 2,
    'title' => 'Find My Stapler',
    'event_type' => 'meeting',
  ),
)

 

array_multisort()按2个键的值排序

$arr = array(
  '0' => array(
    'id' => 3,
    'age' => 27
  ),
  '1' => array(
    'id' => 5,
    'age' => 50
  ),
  '2' => array(
    'id' => 4,
    'age' => 44
  ),
  '3' => array(
    'id' => 3,
    'age' => 78
  ) 
);
foreach ( $arr as $key => $row ){
  $id[$key] = $row ['id'];
  $age[$key] = $row ['age'];
}
array_multisort($id, SORT_ASC, $age, SORT_DESC, $arr);
print_r($arr);

结果:

Array
(
    [0] => Array
        (
            [id] => 3
            [age] => 78
        )

    [1] => Array
        (
            [id] => 3
            [age] => 27
        )

    [2] => Array
        (
            [id] => 4
            [age] => 44
        )

    [3] => Array
        (
            [id] => 5
            [age] => 50
        )
)

 

array_multisort()按3个键的值排序

$array1 = array(
      0=>array('id'=>8,'name'=>'Apple','age'=> 18),
      1=>array('id'=>8,'name'=>'Bed','age'=>17),
      2=>array('id'=>5,'name'=>'Cos','age'=>16),
      3=>array('id'=>5,'name'=>'Cos','age'=>14)
);
function sortArrByManyField(){
  $args = func_get_args();
  if(empty($args)){
    return null;
  }
  $arr = array_shift($args);
  if(!is_array($arr)){
    throw new Exception("The first argument is not an array");
  }
  foreach($args as $key => $field){
    if(is_string($field)){
      $temp = array();
      foreach($arr as $index=> $val){
        $temp[$index] = $val[$field];
      }
      $args[$key] = $temp;
    }
  }
  $args[] = &$arr;
  call_user_func_array('array_multisort',$args);
  return array_pop($args);
}
$arr = sortArrByManyField($array1,'id',SORT_ASC,'name',SORT_ASC,'age',SORT_DESC);
print_r($arr);

结果:

Array
(
    [0] => Array
        (
            [id] => 5
            [name] => Cos
            [age] => 16
        )

    [1] => Array
        (
            [id] => 5
            [name] => Cos
            [age] => 14
        )

    [2] => Array
        (
            [id] => 8
            [name] => Apple
            [age] => 18
        )

    [3] => Array
        (
            [id] => 8
            [name] => Bed
            [age] => 17
        )
)

以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家
Link to post
Link to comment
Share on other sites

 Share

discussion group

discussion group

    You don't have permission to chat.
    • Recently Browsing   0 members

      • No registered users viewing this page.
    ×
    ×
    • Create New...