如何在php中基于键对关联数组进行排序

时间:2014-08-09 15:21:05

标签: php sorting multidimensional-array

我正在使用自定义排序功能构建嵌套菜单。我被困在排序每个菜单的子菜单项。 如何对用户定义的订单的关于,服务等的子菜单项进行排序? 任何帮助将不胜感激。

Array
(
    [About] => Array
        (
            [0] => Array
                (
                    [0] => About us
                    [1] => about.php
                )
            [5] => Array
                (
                    [0] => Who we are
                    [1] => who-we-are.php
                )

        )

    [Services] => Array
        (
            [5] => Array
                (
                    [0] => Web Design
                    [1] => web-design.php
                )

            [10] => Array
                (
                    [0] => Web development
                    [1] => web-development.php
                )

            [15] => Array
                (
                    [0] => SEO
                    [1] => seo.php
                )

        )
)

1 个答案:

答案 0 :(得分:0)

我们将分别对每个子菜单数组(例如关于我们,服务)进行排序。但是如果我们添加一个外部循环,我们可以立即对它们进行排序

foreach ($subMenuArray as $key => $row) 
{
    $innerArray = $row;        // This is the array that holds the menu items 
    $value = $row[0];          // That is the word About us, Who we are
    // Here we build an array that holds the actual values we want to sort.
    $sortingReference[$key] = $value;
}

// Using array_multisort we are sorting our main array 
// referencing to the array we built above
// Sort the subMenuArray with menu items descending
array_multisort($sortingReference, SORT_DESC, $subMenuArray);