我想编写一个函数来获取父母的孩子。 get_children
应该返回$this_parent_id
个孩子的数组。
/* $pages array */
Array
(
[0] => Pages Object
(
[id_page] => 1
[str_title] => index
[id_parent] => 0
)
[1] => Pages Object
(
[id_page] => 10
[str_title] => download
[id_parent] => 0
)
[2] => Pages Object
(
[id_page] => 11
[str_title] => about us
[id_parent] => 1
)
[3] => Pages Object
(
[id_page] => 12
[str_title] => contact us
[id_parent] => 1
)
[4] => Pages Object
(
[id_page] => 13
[str_title] => members
[id_parent] => 1
)
)
我想在条件为真时将子数组推送到数组中。
print_r(get_children(1, $pages));
function get_children($this_parent_id, $family) {
foreach($family as $page) {
if ($page->id_parent == $this_parent_id) {
/* here I need to append $page to $temp_array
isset($temp_array) ? $temp_array = array($temp_array, (array)$page) : $temp_array = (array)$page; */
}
}
return $temp_array;
}
答案 0 :(得分:0)
array_push()
是您正在寻找的功能吗?
function get_children($this_parent_id, $family) {
$temp_array = array();
foreach($family as $page) {
if ($page->id_parent == $this_parent_id) {
array_push($temp_array, $page);
}
}
return $temp_array;
}
答案 1 :(得分:0)
print_r(get_children(1, $pages));
function get_children($this_parent_id, $family)
{
global $temp_array;
foreach ($family as $page) {
if ($page->id_parent == $this_parent_id) {
isset($temp_array) ? $temp_array[] = (array) $page : $temp_array = array((array) $page);
}
}
return $temp_array;
}
答案 2 :(得分:0)
错误可能是由于行
中的分配isset($temp_array) ? $temp_array = array($temp_array, (array)$page) : $temp_array = (array)$page;
以下功能代码应该可以正常工作。
function get_children($this_parent_id, $family)
{
$temp_array = array();
foreach ($family as $page) {
if ($page->id_parent == $this_parent_id) {
array_push($temp_array,$page);
}
}
return $temp_array;
}