omg
omg

Reputation: 140072

Is there a built-in sortByKey() function to sort array rows by a passed in column name?

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)

Upvotes: 0

Views: 180

Answers (2)

RageZ
RageZ

Reputation: 27323

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

Upvotes: 2

Cem Kalyoncu
Cem Kalyoncu

Reputation: 14603

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

Upvotes: 0

Related Questions