简体   繁体   English

PHP中是否有内置的sortByKey()函数?

[英]Is there a built-in sortByKey() function in PHP?

Say,$arr contains multiple sub-arrays with the key "pos", 假设$ arr包含多个键为“ pos”的子数组,

$arr = sortByKey($arr,'pos');

After that the sub-array with smallest "pos" value will be ordered first,and so on. 此后,将对“ pos”值最小的子数组进行排序,依此类推。

EDIT 编辑

$sub1 = array('pos' => 2);
$sub2 = array('pos' => 1);
$arr = array($sub1,$sub2);
$arr = sortByKey($arr,'pos');

After this function,$arr will be array($sub2,$sub1) 执行此函数后,$ arr将为array($ sub2,$ sub1)

see the ksort function. 请参阅ksort函数。

here come the manual of the function. 这是功能手册

sorry also I think you are ccase you are more looking into uasort you would be able to define a function to compare each of your elements and sort them 抱歉,我想您是ccase,您正在研究uasort,您将能够定义一个函数来比较每个元素并对其进行排序

// Array to be sorted

print_r($array);

// Sort and print the resulting array
uasort($array, create_function('$a,$b', 'return $a[\'pos\'] == $b[\'pos\'] ? 0 : (($a[\'pos\'] < $b[\'pos\']) ? -1 : 1);'));
print_r($array);

have to be tested not sure about the double ? 必须进行测试,不确定该加倍吗? operator ... 操作员...

Cheer 欢呼

Let me write you a function. 让我为您编写一个函数。 Its not tested. 它未经测试。

function subarray_sort($array, $subkey) {
  $sortarray=array();
  foreach($array as $item) {
      $sortarray[]=$item[$subkey];
  }

  array_multisort($sortarray, $array);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM