按名称合并/排序数组

时间:2018-11-02 23:28:26

标签: php arrays algorithm sorting

我尝试按名称对数组进行排序。我想创建一个类似于菜单的结构。首先,我允许一个函数将值写入数组。然后,我想将所有子页面分配给父页面(由结构,例如URL产生)。 出

array
(
     [0] => array
         (
             [Pages] => coreViewSites
         )

     [1] => array
         (
             [Pages / Create] => create coreView
         )

     [2] => array
         (
             [Pages / Duplicate] => coreViewSites
         )

     [3] => array
         (
             [Pages / Anarchy] => coreViewSites
         )

     [4] => array
         (
             [User] => coreViewUser
         )

)

应该像这样的数组

array
(
     [Pages] => Array
         (
             [0] => ABC
             [Create] => ABC
             [Duplicate] => ABC
             [Anarchy] => ABC
         )

     [User] => ABC
)

成为。

您知道我该如何解决吗?

1 个答案:

答案 0 :(得分:1)

假设菜单项是在父母先于孩子的情况下订购的,那么您可以这样做:

$menu = [];
foreach($input as $path) {
    $keys = explode(" / ", key($path)); // Extract the individual menu titles
    $last = array_pop($keys); // Pull the last one from it
    $loc = &$menu;
    foreach($keys as $key) {
        // Create menu item if it does not exist yet
        if (!isset($loc[$key])) $loc[$key] = []; 
        // When a menu gets sub-menu, move the title in index 0 of a new array
        if (!is_array($loc[$key])) $loc[$key] = [$loc[$key]];
        $loc = &$loc[$key]; // Set the pointer to that submenu
    }
    $loc[$last] = reset($path); // At the deepest level assign the menu title.
}
// Print result:
var_export($menu);

输出:

array (
    'Pages' => array (
        0 => 'coreViewSites',
        'Create' => 'create coreView',
        'Duplicate' => 'coreViewSites',
        'Anarchy' => 'coreViewSites',
    ),
    'User' => 'coreViewUser',
)