我需要一些帮助。我对算法的了解很少。我不能在PHP中编写一个返回所有最新子节点的递归函数。
假设我们的数组如下所示:
Array
(
[0] => Array
(
[id_category] => 1
[name] => Accueil
[id_parent] => 0
)
[1] => Array
(
[id_category] => 2
[name] => Accessoires
[id_parent] => 1
)
[2] => Array
(
[id_category] => 3
[name] => Merchandising
[id_parent] => 1
)
[3] => Array
(
[id_category] => 4
[name] => Pièces détachées
[id_parent] => 1
)
[4] => Array
(
[id_category] => 5
[name] => Excavateur
[id_parent] => 4
)
[5] => Array
(
[id_category] => 6
[name] => série 100
[id_parent] => 5
)
[6] => Array
(
[id_category] => 7
[name] => above
[id_parent] => 6
)
[7] => Array
(
[id_category] => 8
[name] => système hydraulique
[id_parent] => 7
)
[8] => Array
(
[id_category] => 9
[name] => série 200
[id_parent] => 5
)
[9] => Array
(
[id_category] => 10
[name] => thru
[id_parent] => 6
)
[10] => Array
(
[id_category] => 11
[name] => Compaction
[id_parent] => 4
)
[11] => Array
(
[id_category] => 12
[name] => système électrique
[id_parent] => 7
)
)
我想getLastChildren(5)或getLastChildren(6)或getLastChildren(7),该函数返回一个答案数组(“8”,“12”)
我会试着举个例子。
如果我选择5类:= 6和9是孩子。
我透过孩子看。孩子6有两个孩子,7和10,孩子9:没有孩子。
我在孩子名单中加了9个。
7岁的孩子有两个孩子,8岁和12岁.8岁没有孩子。 12没有孩子。我加8和12.
所以我们返回(9,8,12)10没有孩子。我还补充道。
最后我(9,8,12,10)
那么我会做什么,如果我搜索“类别7中的所有最后一个孩子”=> 8和12.我希望我的解释“更清楚一点。”
答案 0 :(得分:2)
我会做那样的事情:
$array = array(
array (
'id_category' => 1,
'name' => 'Accueil',
'id_parent' => 0,
),
array (
'id_category' => 2,
'name' => 'Accessoires',
'id_parent' => 1,
),
array (
'id_category' => 3,
'name' => 'Merchandising',
'id_parent' => 1,
),
array (
'id_category' => 4,
'name' => 'Pièces détachées',
'id_parent' => 1,
),
array (
'id_category' => 5,
'name' => 'Excavateur',
'id_parent' => 4,
),
array (
'id_category' => 6,
'name' => 'série 100',
'id_parent' => 5,
),
array (
'id_category' => 7,
'name' => 'above',
'id_parent' => 6,
),
array (
'id_category' => 8,
'name' => 'système hydraulique',
'id_parent' => 7,
),
array (
'id_category' => 9,
'name' => 'série 200',
'id_parent' => 5,
),
array (
'id_category' => 10,
'name' => 'thru',
'id_parent' => 6,
),
array (
'id_category' => 11,
'name' => 'Compaction',
'id_parent' => 4,
),
array (
'id_category' => 12,
'name' => 'système électrique',
'id_parent' => 7,
),
);
我分割数据和代码,这是代码:
$children = array();
function getLastChildren($array, $parent) {
global $children;
foreach ($array as $key => $value) {
if ($value['id_parent'] == $parent) {
if (hasChild($array, $value['id_category'])) {
getLastChildren($array, $value['id_category']);
} else {
$children[] = $value['id_category'];
}
}
}
}
function hasChild($array, $parent) {
foreach ($array as $key => $value) {
if ($value['id_parent'] == $parent) {
return true;
}
}
return false;
}
getLastChildren($array, 5);
print_r($children);
<强>输出:强>
Array
(
[0] => 8
[1] => 12
[2] => 10
[3] => 9
)