I'm using a multidimensional PHP array to keep track of objects, like this:
Array(
["name1"] => Array(
["data"] => Array(
["children"] => Array(
["name2"] => Array(
["data"] => Array(
["otherData"] => 2
)
),
["name3"] => Array(
["data"] => Array()
)
)
)
),
["name4"] => Array(
["data"] => Array(
["someRandomValue"] => "hi"
)
)
)
This could be any number of levels, and so I would
need a recursive function to add a new object into it.
I'd like to do something like this:
function addToArray($item, $array) {
if ($item-getData('insertBefore')) {
//...
}
if ($item-getData('insertAfter')) {
//...
}
if ($item-getData('parent')) {
//...
}
foreach($array as &$arraySlice) {
//..magic here
}
}
Basically the function would try to honor the 3 data options
parent
, insertBefore
and insertAfter
as best as it can.
If conflicting info with before & after it would give an error
and with missing parent (and before/after) info just append as
last index, after "name4".
So that a new item called name5
with parent
set to name1
and
insertBefore
set to name3
is inserted like this:
Array(
["name1"] => Array(
["data"] => Array(
["children"] => Array(
["name2"] => Array(
["data"] => Array(
["otherData"] => 2
)
),
["name5"] => Array(
["data"] => Array(
["parent"] => "name1",
["insertBefore"] => "name3"
)
),
["name3"] => Array(
["data"] => Array()
)
)
)
),
["name4"] => Array(
["data"] => Array(
["someRandomValue"] => "hi"
)
)
)
Any suggestions? I can't seem to get it right in my attempts. Another function to remove any "nameX" entry would be great too.
EDIT: here's my latest try before I got confused enought to give up
function addToArray($item, $array) {
$parent = isset($item->getData('parent')) ? $item->getData('parent') : null;
$before = isset($item->getData('insertBefore')) ? $item->getData('insertBefore') : null;
$after = isset($item->getData('insertAfter')) ? $item->getData('insertAfter') : null;
$parentFound = null;
$prevPart = null;
// use & in the loop to work with a reference
foreach($layout as $key => &$part) {
if ($key == $parent) {
$parentFound = 1;
}
if ($parentFound || !$parent) {
if ($after) {
//..
}
if ($before) {
//..
}
//eh, erhm..
} else if ($part['data']['children']) {
if (addToArray($item, $part)) {
return true;
}
}
$prevPart = $part;
}
return false;
}