我有这样的数组构建来自表示cms的单个页面的数据库中的数据:
$page =
Array
(
[title] => mein produkt
[NavID] => 200
[parents] => Array
(
[0] => 0
[1] => 3
[2] => 200
)
)
我需要把它放到另一个代表sitemap的多维数组中:
$map =
Array
(
[NavID] => 0
[0] => Array
(
[childs] => Array
(
[1] => Array
(
[title] => home
[NavID] => 1
)
[2] => Array
(
[title] => impressum
[NavID] => 2
[childs] => Array
(
[100] => Array
(
[title] => startseite
[NavID] => 100
[parents] => Array
(
[0] => 0
[1] => 2
[2] => 100
)
)
)
)
[3] => Array
(
[title] => produkte
[NavID] => 3
)
)
)
)
如您所见,我将数组的结构作为parents
上的数组值。
所以我想用手做的就是这样:
$map[0]['childs'][3]['childs'][200] = $page;
如何选择具有数组值$page['parents']
的多维数组?
感谢您帮助我。
答案 0 :(得分:1)
以这种方式访问$page['parents'][KEY]
值时,您可以直接使用$map
作为键:
$map[$page['parents'][0]]['childs'][$page['parents'][1]]['childs'][$page['parents'][2]] = $page;
随着树木的增长,我真的建议用直接变量缩短它:
$par = $page['parents'];
$map[$par[0]]['childs'][$par[1]]['childs'][$par[2]] = $page;
要动态转到正确的节点,只需使用引用遍历父母:
$tmp = &$map;
$first = true;
foreach ($page['parents'] as $parent) {
if ($first) { // Quick workaround to skip the first node without 'childs' key
$tmp = &$tmp[$parent];
$first = false;
continue;
}
$tmp = &$tmp['childs'][$parent];
}
$tmp = $page;