我在寻找,但我找不到我需要的东西。
源结构是从mysql数据库动态生成菜单数组结构:
array (
2 => array (
'title' => 'item',
'children' => array (
10 => array (
'title' => 'item',
'children' => array (
14 => array (
'title' => 'item',
),
15 => array (
'title' => 'item',
),
16 => array (
'title' => 'item',
'children' => array (
23 => array (
'title' => 'item',
),
24 => array (
'title' => 'item',
),
),
),
17 => array (
'title' => 'item',
'children' => array (
20 => array (
'title' => 'item',
),
),
),
18 => array (
'title' => 'item',
),
19 => array (
'title' => 'item',
),
32 => array (
'title' => 'item',
'children' => array (
33 => array (
'title' => 'item',
),
),
),
59 => array (
'title' => 'item',
),
60 => array (
'title' => 'item',
'children' => array (
61 => array (
'title' => 'item',
),
62 => array (
'title' => 'item',
),
),
),
67 => array (
'title' => 'item',
),
),
),
12 => array (
'title' => 'item',
),
13 => array (
'title' => 'item',
),
),
),
)
我需要传递所有记录并根据需要将新值添加到foreach实际所在的当前位置。现在我可以使用此功能来检查记录:
function categorize($menu, $level = 0)
{
foreach ($menu as $key => &$data)
{
if (isset ($data['children']))
{
categorize($data['children'], ($level + 1));
}
}
}
但不知道如何将新值添加到正确的位置。 输出必须如下所示:
array (
2 => array (
'level' => 0,
'first-item' => true,
'title' => 'item',
'children' => array (
10 => array (
'level' => 1,
'first-item' => true,
'title' => 'item',
'children' => array (
14 => array (
'level' => 2,
'first-item' => true,
'title' => 'item',
),
15 => array (
'level' => 2,
'title' => 'item',
),
16 => array (
'level' => 2,
'title' => 'item',
'children' => array (
23 => array (
'level' => 3,
'first-item' => true,
'title' => 'item',
),
24 => array (
'level' => 3,
'title' => 'item',
),
),
),
17 => array (
'level' => 2,
'title' => 'item',
'children' => array (
20 => array (
'level' => 3,
'title' => 'item',
),
),
),
18 => array (
'level' => 2,
'title' => 'item',
),
19 => array (
'level' => 2,
'title' => 'item',
), ....
感谢您的帮助
答案 0 :(得分:0)
您可以使用引用和递归来实现所需的输出:
function processTitles(array &$titles, $level = 0) {
$i = 0;
foreach ($titles as &$title) {
$title['level'] = $level;
$title['first-item'] = ++$i === 1;
if (!empty($title['children'])) {
processTitles($title['children'], ++$level);
}
}
}
$titles = [
// The input data that you posted
];
processTitles($titles);
var_dump($titles);