我正在创建一个导航栏。在这里我从数据库中获得价值。在我的数据库中有三列page_name
,main_page
,sub_page
。
代表这样:
ID | Page Name | Main Page | Sub Page |
1 | Home | 1 | 0 |
2 | About | 1 | 0 |
3 | Our Work | 0 | 2 |
4 | Contact | 1 | 0 |
Main Page
,那么main_page
= 1
和sub_page
= 0
。Sub Page
,那么其main_page
= 0
和sub_page
id
main_page
。{/ li} >
我从此查询中获取数据库中的这些值:
$query = "SELECT * FROM subjects";
$result = $this->db->query($query)->result_array();
检查我的结果是Main Page
还是Sub Page
并将其添加到数组中
foreach($result as $row){
if ($row['main_page'] == '1') {
$main_page[] = $row['page_name'];//if main page the add them in array
}else{
$result1 = "";
$query1 = "SELECT page_name FROM subjects WHERE id = '$row[sub_page]'";//getting name of main_page
$result1 = $this->db->query($query1)->result_array();
$main_page_name = $result1['0']['page_name'];
$sub_page = $row['page_name'];
echo $main_page_name; echo "<br/>";
$main_sub[] = array('main_page' => $main_page_name, 'sub_page' => $sub_page);//if sub page add main page name and sub page
}
}
之后它正在向我推测这个结果:
Array
(
[0] => Home
[1] => About
[2] => Contact
)
Array
(
[0] => Array
(
[main_page] => About
[sub_page] => Our Work
)
)
如何合并这两个数组以获得如下数组:
Array
(
[0] => Home
[1] => About
(
[sub_page] => Our Work
)
[2] => Contact
)
答案 0 :(得分:1)
我认为你想要的是这样的
Array(
[0] => array(
"title" => "Home"
),
[1] => array(
"title" => "About",
"sub_page" => array(
[0] => "Our Work"
)
),
[2] => array(
"title" => "Contact"
)
)
通过这样做可以实现上述结果
$pageArray = array();
foreach($result as $row){
if ($row['main_page'] == '1') {
$pageArray[$row['id']]["title"] = $row['page_name'];
}else if($row['sub_page']) {
$pageArray[$row['sub_page']]["sub_page"][] = $row['page_name'];
}
}