数组格式

时间:2017-07-26 19:32:47

标签: php arrays multidimensional-array

我对多维数组有疑问。

我试图通过mysql和php创建嵌套菜单。

当我从这个

创建多维数组时
$ref = [];
$items = [];
foreach($row as $row) {
    $thisRef =& $ref[$row->id];
    $thisRef['parent_id'] = $row->parent_id;
    $thisRef['menu_id'] = $row->menu_id;
    $thisRef['type'] = $row->type;
    $thisRef['id'] = $row->id;
    if($row->parent_id == 0) {
        $items[] =& $thisRef;
    } else {
        $ref[$row->parent_id]['sub'][] =& $thisRef;
    }
}

它生成这样的数组。

Array(
    [0] => Array
        (
            [parent_id] => 0
            [menu_id] => 10
            [type] => p
            [id] => 93
        )
    [1] => Array
        (
            [sub] => Array
                (
                    [0] => Array
                        (
                            [parent_id] => 88
                            [menu_id] => 10
                            [type] => b
                            [id] => 92
                            [sub] => Array
                                (
                                    [0] => Array
                                        (
                                            parent_id] => 92
                                            [menu_id] => 8
                                            [type] => c
                                            [id] => 94
                                        )
                                )
                        )
                     [1] => Array
                        (
                            [parent_id] => 88
                            [menu_id] => 8
                            [type] => c
                            [id] => 90
                        )

                )

            [parent_id] => 0
            [menu_id] => 5
            [type] => p
            [id] => 88
        )
    )
)

和它的好,但我想改变第二个数组键的名称sub我的意思是如果数组都准备好了sub,第二个sub将是subofsub,我希望我解释得很好,我试着用isset检查它和array_key_exists但它只是混淆了我的数组。

1 个答案:

答案 0 :(得分:0)

老实说,并没有真正关注这个问题,并且与参考文章有点混淆。

你只是想做这样的事吗?

<?php

$ref   = [];
$items = [];
$subCount = 0;

foreach ($row as $row) {
    $thisRef = &$ref[$row->id];
    $thisRef['parent_id'] = $row->parent_id;
    $thisRef['menu_id'] = $row->menu_id;
    $thisRef['type'] = $row->type;
    $thisRef['id'] = $row->id;
    if($row->parent_id == 0) {
        $items[] = &$thisRef;
    } else {
        $subCount++;
        $ref[$row->parent_id]['sub-' . $subCount][] = &$thisRef;
    }
}