我有一个层次结构或房间和子房间,没有通用数组将其映射出来。相反,我将父代的ids连接到子代。因此,我需要使用一个递归php函数来循环遍历一个房间的子房间和每个房间的子房间,然后构建一个包含所有id的数组。
如果我只是将每个id输出为一个字符串,我会这样做
function get_all_child_subrooms_recursive($rid) {
$subrooms = get_all_subrooms($rid); // a function that grabs an array of direct children room id's to the parent room ($rid)
if ($subrooms == "") {
return;
} else {
foreach ($subrooms as $subroom) {
$rid = $subroom;
echo $rid .',';
get_all_child_subrooms_recursive($rid);
}
}
}但我需要将此数据作为包含所有id的平面数组返回
发布于 2019-12-20 01:50:03
关于平面数组,我假设你指的是一维数组。将它们作为字符串输出是一个很好的开始,只需使用array_push()将它们添加到数组中
$arr = array();
function get_all_child_subrooms_recursive($rid, &$arr) {
$subrooms = get_all_subrooms($rid); // a function that grabs an array of direct children room id's to the parent room ($rid)
if ($subrooms == "") {
return;
} else {
foreach ($subrooms as $subroom) {
array_push(arr, $subroom, get_all_child_subrooms_recursive($subroom, $arr));
}
}
}https://stackoverflow.com/questions/59413644
复制相似问题