Given an array:
0 => (
[parent_id] => null,
[name] => "Root"
[children] => array(
10 => array(
[parent_id] => 0,
[name] => "Category A",
[children] => array(
30 => array(
[parent_id] => 10,
[name] => "Category C"
)
)
),
20 => array(
[parent_id] => 0,
[name] => "Category B"
)
)
)
I need to return an array of string representations of those paths...
array(
[0] => "Root",
[10] => "Root > Category A",
[30] => "Root > Category A > Category C",
[20] => "Root > Category B"
)
I've been messing around doing this recursively but I'm having some trouble doing it efficiently. Are there simple ways to do this that I'm just overlooking?
EDIT:
Solution is simply a slightly modified version of Alexander Varwijk's answer. A few tweaks to handle non-existent children, calling the function recursively via FUNCTION constant so it's easy to change the function name and a change from array_merge to the + operator to combine the arrays in order to preserve keys.
function flatten($data, $prefix = "", $item_seperator = "/") {
$seperator = $prefix == "" ? "" : $item_seperator;
$return = array();
if (is_array($data)) {
foreach($data as $key => $value) {
$return[$value["endeca_id"]] = $prefix . $seperator . $value["url_key"];
if(array_key_exists("children", $value))
{
$return = $return + call_user_func(__FUNCTION__, $value["children"], $prefix . $seperator . $value["url_key"], $item_seperator);
}
}
}
return $retur开发者_JS百科n;
}
I liked this challenge, this should do it:
<?php
$start = array(
0 => array(
'parent_id' => null,
'name' => "Root",
'children' => array(
10 => array(
'parent_id' => 0,
'name' => "Category A",
'children' => array(
30 => array(
'parent_id' => 10,
'name' => "Category C"
)
)
),
20 => array(
'parent_id' => 0,
'name' => "Category B"
)
)
)
);
function recurse($data, $prefix = '') {
$seperator = ($prefix == '' ? '' : ' > ');
$return = array();
if (is_array($data)) {
foreach($data as $key => $value) {
$return[$key] = $prefix . $seperator . $value['name'];
$return = array_merge($return, recurse($value['children'],$prefix . $seperator . $value['name']));
}
}
return $return;
}
print_r(recurse($start));
?>
精彩评论