【问题标题】:How to sort associative array based on key in php如何根据php中的键对关联数组进行排序
【发布时间】:2014-08-09 15:21:05
【问题描述】:

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

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
                )

        )
)

【问题讨论】:

  • 看看array multisort。如果还是找不到解决办法。我可以举个例子。
  • “用户定义的订单”是什么意思?用户应该能够以他们想要的任何顺序放置菜单和子菜单? (例如,将服务放在关于之前?然后按照“Web 开发”、“SEO”和“Web 设计”的顺序放置服务中的不同子菜单?
  • 您好,感谢您的回复。我已经尝试过 usort、array multisort 等,但我没有成功。我们将不胜感激。
  • @Lenny 是的,你是对的。我正在为该功能使用可排序的 jQuery ui。

标签: php sorting multidimensional-array


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2013-05-19
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
  • 2011-07-26
相关资源
最近更新 更多