简体   繁体   中英

help sorting this array

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
        )

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

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

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