tags:

views:

42

answers:

2

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)

A: 

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);
}
Cem Kalyoncu
+2  A: 

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

RageZ
No,it order by the key,but I need it to order by the value with a specified key.
Shore
I have modified.
RageZ
So it need 2 functions totally?
Shore
you can use create_function to make the cmp function on the fly ...
RageZ
Sorry, I see you have added the proper answer now, but SO won't let me change -1 to +1. :-S
too much php
Can you edit it again?
Shore
yeah just a sec
RageZ
thanks I got -2 on that one somehow lol ... any way thanks
RageZ