简体   繁体   中英

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

Say,$arr contains multiple sub-arrays with the key "pos",

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

After that the sub-array with smallest "pos" value will be ordered first,and so on.

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)

see the ksort function.

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

// 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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