1
我想獲取所有菜單項存儲在數據庫中作爲一個數組(兩個數組類型在一個遞歸合併)。以下是我想出了這麼遠:從數據庫構建一個多維數組
// function to push associative array elements recursively
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
$menu_array = $dropdown = $single = array();
// getting menu items (sections)
$get_sections = Db::query("SELECT * FROM `sections` ORDER BY `place` ASC");
if($get_sections){
foreach($get_sections as $menu_items){
$menu_item_id = $menu_items['key_id'];
// getting sub-sections (in any)
$get_children = Db::query("SELECT `id_lng`, `title`, `url`, `parent` FROM `sections` WHERE `lng`.`key_id` = `sections`.`id` AND `parent` = '$menu_item_id' AND `key_type` = '1' AND `published`= '1' ORDER BY `place` ASC ");
if(mysqli_num_rows($get_children) > 0){
foreach($get_children as $kids){
// here I need to add all "kids" recursively so it will be like:
// [Our Services] => Array
// (
// [Service One] => service-one.php
// [Service Two] => service-two.php
// )
$dropdown = array($menu_items['title'] => array($kids['title'] => $kids['url']));
}
} else{
// if there are no "kids" to form a dropdown menu - form an array of this type:
// [Single Menu Item 1] => singe-menu-item-1.php
$single = array_push_assoc($single, $menu_items['title'], $menu_items['url']);
}
我有兩個問題:
1)我已經找到了如何推動關聯數組中循環,但不能肯定該怎麼做多維數組($dropdown
)
2)我知道如何合併兩個數組,但我需要的是在一個循環中都要加入一個接一個 - 我非常希望得到這個類型的數組:
[Single Menu Item 1] => singe-menu-item-1.php
[Our Services] => Array
(
[Service One] => service-one.php
[Service Two] => service-two.php
)
[Single Menu Item 2] => singe-menu-item-2.php
[Single Menu Item 3] => singe-menu-item-3.php
[Contact us] => Array
(
[email us] => email.php
[visit us] => visit.php
[call us] => call.php
)
不要擔心不測試它。大多數PHP代碼未經測試。 – Fuser97381
Rasclatt,mate - 該死的......如此怪異的容易......呃......我想的是一個完全錯誤的方向......非常感謝,陛下! – Rossitten
沒問題,有時很容易過度考慮問題。我一直這樣做!如果你想要一個真正的遞歸和更復雜的解決方案,這是一個可以工作的解決方案,但它需要一個不同的方法:http://stackoverflow.com/questions/41031756/create-dynamic-menu-array-using-php/41042166#41042166 – Rasclatt