我正在尝试使用以下代码从数组的父ID中获取所有孩子
$temp = array();
$temp[] = array("id"=>"2", "parent_id"=>null);
$temp[] = array("id"=>"3", "parent_id"=>"5");
$temp[] = array("id"=>"6", "parent_id"=>"3");
$temp[] = array("id"=>"7", "parent_id"=>"8");
$temp[] = array("id"=>"5", "parent_id"=>"2");
function getChildrenIds(array $elements, $parentId) {
$children = array();
$children_number = "";
foreach($elements as $element) {
if($element["parent_id"] === $parentId) {
$children[] = $element["id"];
$children[] = getChildrenIds($elements, $element["id"]);
}
}
return $children;
}
print_r(getChildrenIds($temp, "2"));
我的输出低于
Array
(
[0] => 5
[1] => Array
(
[0] => 3
[1] => Array
(
[0] => 6
[1] => Array
(
)
)
)
)
但是我需要像下面这样的输出,并将所有子ID放在一个数组中
Array
(
[0] => 5
[1] => 3
[2] => 6
)
我在这里想念的是什么?