PHP多维数组排序

时间:2013-10-12 13:20:43

标签: php arrays sorting multidimensional-array

我正在尝试根据[sort_order]对此多维数组进行排序。

我搜索了许多与没有成功相关的主题

我可以在这里得到一些帮助吗?

目标是对数组进行排序,以便按以下顺序获取数组: 1 - [post_images] 2 - [localizacao] 3 - [post_title] 4 - [category]

先谢谢。

Array
(
    [[#taxonomy_name#]] => Array
        (    
            [post_title] => Array
                (
                    [name] => post_title
                    [show_in_email] => 1
                    [sort_order] => 3
                    [options] => Array
                        (
                            [0] => 
                        )

                )

            [post_images] => Array
                (
                    [name] => post_images 
                    [is_active] => 1
                    [show_on_listing] => 1
                    [show_on_detail] => 1
                    [sort_order] => 1
                    [options] => Array
                        (
                            [0] => 
                        )

                )

            [category] => Array
                (
                    [name] => category
                    [is_require] => 1
                    [is_active] => 1
                    [show_on_listing] => 1
                    [show_on_detail] => 1
                    [show_in_email] => 1
                    [sort_order] => 4
                    [options] => Array
                        (
                            [0] => 
                        )

                )

            [localizacao] => Array
                (
                    [name] => localizacao
                    [label] => Localização
                    [htmlvar_name] => localizacao
                    [sort_order] => 2
                    [options] => Array
                        (
                            [0] => 
                        )

                )

        )

)

2 个答案:

答案 0 :(得分:0)

您可能会发现usort很有用,它允许您使用如下的回调函数进行排序:

// The function which will do your comparisons:
function sortOrderCompare ($a, $b) {
    $aOrder = $a['sort_order'];
    $bOrder = $b['sort_order'];

    if ($aOrder == $bOrder) {
        // A and B have the same order
        return 0;
    }else if ($aOrder < $bOrder) {
        //A comes before B 
        return -1;
    }else{
        // B comes before A
        return 1; 
    }

}

usort($array['[#taxonomy_name#]'], "sortOrderCompare");

答案 1 :(得分:0)

您可以使用array_multisort

根据您的数组结构,它看起来像这样:

foreach( $posts as $post=>$row )
{
    $sort_order[$post]  = $row['sort_order'];
}
array_multisort( $sort_order, SORT_ASC, $posts );