1
データベースに格納されているすべてのメニューアイテムを配列として取得しようとしています(再帰的に1つにマージされた2つの配列タイプ)。ここで私は今のところ出ているものです:データベースから多次元配列を構築する
// 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']);
}
私は2つの問題を抱えて:
1)私はそれを行う方法をループ内で連想配列をプッシュする方法を考え出したが、特定されていません多次元配列($dropdown
)
2)と私は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 - damn ...そんなに怖い... heh ...私はまったく間違った方向に考えていた...ありがとう、恥ずかしがり屋! – Rossitten
問題はありませんが、問題を過度に考えるのは簡単です。私はいつもそれをする!本当に再帰的で複雑な解決策が必要な場合は、ここで解決する方法がありますが、少し異なるアプローチが必要です。http://stackoverflow.com/questions/41031756/create-dynamic-menu-array-using-php/41042166#41042166 – Rasclatt