Reputation: 313
I got arrays like this build upon data from a database representing single pages of a cms:
$page =
Array
(
[title] => mein produkt
[NavID] => 200
[parents] => Array
(
[0] => 0
[1] => 3
[2] => 200
)
)
And I need to put that into an other multidimensional array like this representing the 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
)
)
)
)
As you see, I got the structure of the array as the array value on parents
.
So what I would do by hand is putting this like:
$map[0]['childs'][3]['childs'][200] = $page;
Put how can I select the multidimensional array with my array value $page['parents']
?
Thanks for helping me out.
Upvotes: 1
Views: 306
Reputation: 5090
You can directly use $page['parents'][KEY]
as keys when accessing $map
values that way :
$map[$page['parents'][0]]['childs'][$page['parents'][1]]['childs'][$page['parents'][2]] = $page;
As your tree grows, I'd really suggest to shorten it with a direct variable :
$par = $page['parents'];
$map[$par[0]]['childs'][$par[1]]['childs'][$par[2]] = $page;
To dynamically go to the correct node, just loop over your parents using references :
$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;
Upvotes: 1