views:

42

answers:

2

So I am looking to sort the multi dimensional array below by "fk_page_id" ascending. Does anyone have any pointers. I think usort() is where I have to look but it seems like I cant find anyone with my specific array structure.

Array
    (

    [0] => Array

        (
            [title] => subpage of subpage!
            [id] => 5
            [long_title] =>
            [fk_page_id] => 4                                
        )

    [1] => Array
        (
            [title] => about us subpage
            [id] => 4
            [long_title] => 
            [fk_page_id] => 2
        )

    [2] => Array
        (
            [title] => about us
            [id] => 2
            [long_title] => 
            [fk_page_id] => 1
        )

)
+4  A: 
function cmp($a, $b) {
    if($a['fk_page_id'] == $b['fk_page_id']) {
        return 0;
    } else {
        return $a['fk_page_id'] < $b['fk_page_id'] ? -1 : 1;
    }
}

usort($yourarray, 'cmp');
Amber
is there a way to do this dynamically.. a function that does something like sort_array($array,$key,$direction); this does work for what i need though, thanks!
Roeland
A: 

if you're using PHP 5.3+:

define(ASC,1);
define(DESC,-1);

function colsort($array,$col,$order=ASC) {
    usort(
        $array,
        function($a,$b) use($col,$order) {
            return strcmp($a[$col],$b[$col])*$order;
        }
    );
    return $array;
}

colsort($x,'fk_page_id');
stillstanding