Php 将数组推送到空数组中
我想编写一个函数来获取父对象的子对象Php 将数组推送到空数组中,php,arrays,Php,Arrays,我想编写一个函数来获取父对象的子对象get_children应该返回$this_parent\u id子元素的数组 /* $pages array */ Array ( [0] => Pages Object ( [id_page] => 1 [str_title] => index [id_parent] => 0 ) [1] => Page
get_children
应该返回$this_parent\u 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
)
)
我想在条件为true时将子数组推入数组
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;
}
array\u 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;
}
错误可能是因为行中的赋值
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;
}
像
$this\u parent\u id[]=$page
?更改为isset($temp\u array)$临时数组[]=(数组)$page:$临时数组=(数组)$page代码>和工作。谢谢@AlvinWongI试过了,但没用第一个参数应该是
中的数组,而打印时$temp\u array是数组
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;
}