对一个给定的二维数组按照指定的键值进行排序

Posted 盘思动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对一个给定的二维数组按照指定的键值进行排序相关的知识,希望对你有一定的参考价值。

public function set_s(){

$arr = [
[‘one‘ => 6,‘two‘ => 19],
[‘one‘ => 36,‘two‘ => 3],
[‘one‘ => 26,‘two‘ => 3],
[‘one‘ => 2,‘two‘ => 84],
[‘one‘ => 5,‘two‘ => 35],
[‘one‘ => 6,‘two‘ => 56],
[‘one‘ => 7,‘two‘ => 7],
[‘one‘ => 88,‘two‘ => 8],
[‘one‘ => 23,‘two‘ => 22],
[‘one‘ => 1,‘two‘ => 29],
];

$arr1 = $this->array_sort($arr,‘one‘,‘asc‘);
dump($arr1);

echo ‘-------------------------------‘;

$arr2 = $this->array_sort($arr,‘one‘,‘desc‘);
dump($arr2);

}


//对一个给定的二维数组按照指定的键值进行排序
public function array_sort($arr,$keys,$type = ‘asc‘){
$keysvalue = $new_array = array();
foreach ($arr as $k=>$v){
$keysvalue[$k] = $v[$keys];
}
if($type == ‘asc‘){
asort($keysvalue);
}else{
arsort($keysvalue);
}

reset($keysvalue);
foreach ($keysvalue as $k=>$v){
$new_array[$k] = $arr[$k];
}
return $new_array;
}


array(10) {
  [9] => array(2) {
    ["one"] => int(1)
    ["two"] => int(29)
  }
  [3] => array(2) {
    ["one"] => int(2)
    ["two"] => int(84)
  }
  [4] => array(2) {
    ["one"] => int(5)
    ["two"] => int(35)
  }
  [0] => array(2) {
    ["one"] => int(6)
    ["two"] => int(19)
  }
  [5] => array(2) {
    ["one"] => int(6)
    ["two"] => int(56)
  }
  [6] => array(2) {
    ["one"] => int(7)
    ["two"] => int(7)
  }
  [8] => array(2) {
    ["one"] => int(23)
    ["two"] => int(22)
  }
  [2] => array(2) {
    ["one"] => int(26)
    ["two"] => int(3)
  }
  [1] => array(2) {
    ["one"] => int(36)
    ["two"] => int(3)
  }
  [7] => array(2) {
    ["one"] => int(88)
    ["two"] => int(8)
  }
}
-------------------------------
array(10) {
  [7] => array(2) {
    ["one"] => int(88)
    ["two"] => int(8)
  }
  [1] => array(2) {
    ["one"] => int(36)
    ["two"] => int(3)
  }
  [2] => array(2) {
    ["one"] => int(26)
    ["two"] => int(3)
  }
  [8] => array(2) {
    ["one"] => int(23)
    ["two"] => int(22)
  }
  [6] => array(2) {
    ["one"] => int(7)
    ["two"] => int(7)
  }
  [5] => array(2) {
    ["one"] => int(6)
    ["two"] => int(56)
  }
  [0] => array(2) {
    ["one"] => int(6)
    ["two"] => int(19)
  }
  [4] => array(2) {
    ["one"] => int(5)
    ["two"] => int(35)
  }
  [3] => array(2) {
    ["one"] => int(2)
    ["two"] => int(84)
  }
  [9] => array(2) {
    ["one"] => int(1)
    ["two"] => int(29)
  }
}











以上是关于对一个给定的二维数组按照指定的键值进行排序的主要内容,如果未能解决你的问题,请参考以下文章

php 怎样将二维数组键名从新按照0开始排序

PHP中如何对二维数组按某个键值进行排序

php用正则匹配二维数组的键值

二维数组按照指定的字段排序的函数

二维数组按照指定的字段排序的函数

php二维数组按照键值排序的方法