Php 如何从数组中存储的嵌套集合中获取完整路径?
假设我有以下数组:Php 如何从数组中存储的嵌套集合中获取完整路径?,php,arrays,nested,parent-child,traversal,Php,Arrays,Nested,Parent Child,Traversal,假设我有以下数组: Array ( [0] => Array ( [category_id] => 1 [name] => foo [parent_id] => 0 ) [1] => Array ( [category_id] => 2 [name] => bar [parent_id] => 1 ) [2] =>
Array
(
[0] => Array
(
[category_id] => 1
[name] => foo
[parent_id] => 0
)
[1] => Array
(
[category_id] => 2
[name] => bar
[parent_id] => 1
)
[2] => Array
(
[category_id] => 3
[name] => baz
[parent_id] => 0
)
[3] => Array
(
[category_id] => 4
[name] => test
[parent_id] => 2
)
[4] => Array
(
[category_id] => 5
[name] => test2
[parent_id] => 4
)
)
我正在尝试获得以下输出:
foo
foo > bar
baz
foo > bar > test
foo > bar > test > test2
我想我已经把伪代码整理好了,但我想不出我该如何把它变成代码:
$arr = array();
foreach($categories as $category) {
if ($category['parent_id'] > 0) {
$x = find where $categories['category_id'] == $cat['parent_id'];
$arr[] = $x['name'].' > '.$category['name'];
// somehow repeat till parent id is 0
} else {
$arr[] = $category['name'];
}
}
有人有主意吗?谢谢以下是我根据您的阵列制作的函数:
function findParents($array, $parentId, $reset = true) {
static $breadcrumbs;
// reset path on every new lookup
if ($reset == true) {
$breadcrumbs = array();
}
foreach($array as $category) {
if ($parentId == $category['category_id']) {
// append the name of the category
$breadcrumbs[] = $category['name'];
// if a parent exists recursively call this function until no more parent is found
if ($category['parent_id'] > 0) {
findParents($array, $category['parent_id'], false);
}
}
}
// because the function goes the path from in to out, the array needs to be reversed
return array_reverse($breadcrumbs);
}
用法:
foreach($categories as $category) {
// find all parents to the current category
$parents = findParents($categories, $category['category_id']);
echo implode(' > ', $parents);
echo PHP_EOL;
}
输出为:
foo
foo > bar
baz
foo > bar > test
foo > bar > test > test2
下面是我根据您的数组创建的函数:
function findParents($array, $parentId, $reset = true) {
static $breadcrumbs;
// reset path on every new lookup
if ($reset == true) {
$breadcrumbs = array();
}
foreach($array as $category) {
if ($parentId == $category['category_id']) {
// append the name of the category
$breadcrumbs[] = $category['name'];
// if a parent exists recursively call this function until no more parent is found
if ($category['parent_id'] > 0) {
findParents($array, $category['parent_id'], false);
}
}
}
// because the function goes the path from in to out, the array needs to be reversed
return array_reverse($breadcrumbs);
}
用法:
foreach($categories as $category) {
// find all parents to the current category
$parents = findParents($categories, $category['category_id']);
echo implode(' > ', $parents);
echo PHP_EOL;
}
输出为:
foo
foo > bar
baz
foo > bar > test
foo > bar > test > test2
是否尝试将该结果作为新数组获取?是否尝试将该结果作为新数组获取?