用于Childs的PHP数组重组格式

时间:2015-07-25 02:56:19

标签: php arrays

我正在尝试将菜单项列表转换为更有条理的菜单项列表。我不认为这很重要但是如果你好奇这是一个从WordPress安装得到的菜单数组。正如您在第一个菜单中看到的,所有菜单项都列出了子菜单项。我想要做的是采用原始数组并将其转换为更有条理的数组。

我知道它会涉及某种花哨的循环,但我已经停顿了大约一个小时,现在试图想出这个希望有人可以提供帮助。

提前致谢。

  

原始数组

Array (
    [0] => WP_Post Object (
        [ID] => 13
        [menu_item_parent] => 0
        [url] => http://site.dev/
        [title] => Sample Page
        [target] =>
    )

    [1] => WP_Post Object (
        [ID] => 14
        [menu_item_parent] => 0
        [url] => http://site.dev/
        [title] => Sample Page
        [target] =>
    )

    [2] => WP_Post Object (
        [ID] => 15
        [menu_item_parent] => 13
        [url] => http://site.dev/
        [title] => Sample Page
        [target] =>
    )

    [3] => WP_Post Object (
        [ID] => 16
        [menu_item_parent] => 13
        [url] => http://site.dev/
        [title] => Sample Page
        [target] =>
    )

    [4] => WP_Post Object (
        [ID] => 17
        [menu_item_parent] => 0
        [url] => http://site.dev/
        [title] => Sample Page
        [target] =>
    )
)
  

我想要完成的事情

Array (

    [0] => Array (
        [ID] => 13
        [menu_item_parent] => 0
        [url] => http://site.dev/
        [title] => Sample Page
        [target] =>
        [submenu] => Array (
            [0] => Array (
                [ID] => 15
                [menu_item_parent] => 13
                [url] => http://site.dev/
                [title] => Sample Page
                [target] =>
            )

            [1] => Array (
                [ID] => 16
                [menu_item_parent] => 13
                [url] => http://site.dev/
                [title] => Sample Page
                [target] =>
            )
        )
    )

    [1] => Array (
        [ID] => 14
        [menu_item_parent] => 0
        [url] => http://site.dev/
        [title] => Sample Page
        [target] =>
    )

    [4] => Array (
        [ID] => 17
        [menu_item_parent] => 0
        [url] => http://site.dev/
        [title] => Sample Page
        [target] =>
    )

)

1 个答案:

答案 0 :(得分:0)

试试这个:

$new_array = [];
$new_array_ids = [];
$ni = 0;
$sub_array = [];
foreach ($array AS $object) {
    if ($object->menu_item_parent) {
        if (isset($new_array_ids[$object->menu_item_parent])) {
            $new_array[$new_array_ids[$object->menu_item_parent]]['submenu'][] = (array)$object;    
        }
        else {
            $sub_array[] = (array)$object;
        }
    }
    else {
        $new_array[$ni] = (array)$object;
        $new_array[$ni]['submenu'] = [];
        $new_array_ids[$object->ID] = $ni;      
        $ni++;
    }
}

foreach ($sub_array AS $sub) {
    $new_array[$new_array_ids[$sub['menu_item_parent']]]['submenu'][] = $sub;   
}

我没有检查过这个对不起可能的错误。 此外,它仅适用于子类别的深度小于2

的情况