【发布时间】:2019-12-18 09:07:46
【问题描述】:
我似乎无法将孙子数组正确插入它的父子数组。我在下面有这个输出供参考:
array(3) {
[0]=>
array(3) {
["title"]=>
string(6) "test 1"
["url"]=>
string(1) "#"
["child"]=>
array(3) {
[0]=>
array(5) {
["Child-ID"]=>
int(21063)
["title"]=>
string(17) "Case Parts & Mods"
["url"]=>
string(71) "/product-category/case-parts-mods/"
["category"]=>
string(2) "61"
["grandchild"]=>
array(0) {
}
}
[1]=>
array(5) {
["Child-ID"]=>
int(21026)
["title"]=>
string(15) "Child of Test 1"
["url"]=>
string(1) "#"
["category"]=>
string(5) "21026"
["grandchild"]=>
array(0) {
}
}
[2]=>
array(4) {
["GRANDCHILD"]=>
string(27) "GRAND CHILD OF CHILD TEST 1"
["title"]=>
string(21) "Grand Child of test 1"
["url"]=>
string(1) "#"
["category"]=>
string(5) "21065"
}
}
}
[1]=>
array(3) {
["title"]=>
string(6) "test 2"
["url"]=>
string(1) "#"
["child"]=>
array(1) {
[0]=>
array(5) {
["Child-ID"]=>
int(21027)
["title"]=>
string(15) "Child of Test 2"
["url"]=>
string(1) "#"
["category"]=>
string(5) "21027"
["grandchild"]=>
array(0) {
}
}
}
}
[2]=>
array(3) {
["title"]=>
string(6) "test 3"
["url"]=>
string(1) "#"
["child"]=>
array(0) {
}
}
}
我希望将这个孙子数组插入到它所属的名为“grandchild”的子数组键中:
array(4) {
["GRANDCHILD"]=>
string(27) "GRAND CHILD OF CHILD TEST 1"
["title"]=>
string(21) "Grand Child of test 1"
["url"]=>
string(1) "#"
["category"]=>
string(5) "21065"
}
如何使用 array_push() 正确地做到这一点?这是我的输出逻辑代码:
foreach((array)$menu_items as $key => $menu_item) {
if($menu_item->menu_item_parent == 0){
$parent_id = $menu_item->db_id;
$title = $menu_item->title;
$url = $menu_item->url;
array_push($parent, array("title" => $title, "url" => $url, "child" => array()));
}
else if($menu_item->menu_item_parent == $parent_id) {
$child_id = $menu_item->db_id;
$catID = $menu_item->object_id;
$title = $menu_item->title;
$url = $menu_item->url;
array_push($parent[count($parent) - 1]["child"], array("Child-ID" => $child_id ,"title" => $title, "url" => $url, "category" => $catID, "grandchild" => array() ));
} else if($menu_item->menu_item_parent == $child_id) {
$catID = $menu_item->object_id;
$title = $menu_item->title;
$url = $menu_item->url;
array_push( $parent[count($parent) - 1]["child"], array(
"GRANDCHILD" => 'GRAND CHILD OF CHILD TEST 1',
"title" => $title,
"url" => $url,
"category" => $catID
)); /** I"M HAVING THIS PROBLEM **/
}
else{
}
}
【问题讨论】:
标签: php arrays multidimensional-array associative-array