phparrayssortingmultidimensional-array

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)


Solution

  • 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