简体   繁体   English

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

[英]How to sort associative array based on key in php

I am building a nested menu with custom sorting function. 我正在构建具有自定义排序功能的嵌套菜单。 I am stuck in sorting the sub menu items of each menu. 我被困在对每个菜单的子菜单项进行排序的过程中。 How can i sort the sub menu items of About, Services, etc of user defined order? 如何对用户定义顺序的关于,服务等子菜单项进行排序? Any help would be greatly appreciated. 任何帮助将不胜感激。

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
                )

        )
)

We are going to sort each submenu array (eg about us, services) separately. 我们将对每个子菜单数组(例如关于我们,服务)分别进行排序。 But if we add an outer loop we can sort them at once 但是,如果我们添加一个外循环,我们可以立即对其进行排序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM