将嵌套的 PHP 层次数组展平为字符串表示形式
给定一个数组:
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"
)
)
)
我需要返回这些路径的字符串表示形式的数组...
array(
[0] => "Root",
[10] => "Root > Category A",
[30] => "Root > Category A > Category C",
[20] => "Root > Category B"
)
我一直在递归地执行此操作,但在有效执行此操作时遇到了一些麻烦。有没有我忽略的简单方法可以做到这一点?
编辑:
解决方案只是 Alexander Varwijk 答案的稍微修改版本。进行一些调整来处理不存在的子项,通过 FUNCTION 常量递归调用函数,这样就可以轻松更改函数名称,并将 array_merge 更改为 + 运算符以组合数组以保留键。
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 $return;
}
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 $return;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我喜欢这个挑战,应该可以做到:
I liked this challenge, this should do it: