Change PHP code to MVC Codeigniter - php

I've made a recursive function to display the menu as a tree (each domain to have sub domains, and so on). The code works as is with a database, but I want to make it MVC to include it into my Codeigniter project.
I've tried splitting everything related to the database into the model, and so on... but doesn't work. You can see below the raw code, maybe someone can guide me how to change it to the MVC model. Thanks!!
<?php
$result = mysql_query("select id_domeniu, nume_domeniu, parent from domenii");
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
while ($row = mysql_fetch_assoc($result)) {
//creates entry into menus array with current menu id ie. $menus['menus'][1]
$menu['menus'][$row['id_domeniu']] = $row;
//creates entry into parent_menus array. parent_menus array contains a list of all menus with children
$menu['parent_menus'][$row['parent']][] = $row['id_domeniu'];
}
function buildMenu($parent, $menu) {
$html = "";
if (isset($menu['parent_menus'][$parent])) {
$html .= "<ul>";
foreach ($menu['parent_menus'][$parent] as $menu_id) {
if (!isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='#'>" . $menu['menus'][$menu_id]['nume_domeniu'] . "</a></li>";
}
if (isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='#'>" . $menu['menus'][$menu_id]['nume_domeniu'] . "</a>";
$html .= buildMenu($menu_id, $menu);
$html .= "</li>";
}
}
$html .= "</ul>";
}
return $html;
}
?>
<!doctype html>
<html lang=''>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="script.js"></script>
<title>Test</title>
</head>
<body>
<div id='cssmenu'>
<?php echo buildMenu(0, $menu);; ?>
</div>
</body>
<html>
My attempt:
Model:
<?php
class New_menu_model extends CI_Model {
function get_domains() {
$result = $this->db->get ( 'domenii' );
return $result;
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
while ($row = mysql_fetch_assoc($result)) {
//creates entry into menus array with current menu id ie. $menus['menus'][1]
$menu['menus'][$row['id_domeniu']] = $row;
//creates entry into parent_menus array. parent_menus array contains a list of all menus with children
$menu['parent_menus'][$row['parent']][] = $row['id_domeniu'];
}
}
function buildMenu($parent, $menu) {
$html = "";
if (isset($menu['parent_menus'][$parent])) {
$html .= "<ul>";
foreach ($menu['parent_menus'][$parent] as $menu_id) {
if (!isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='#'>" . $menu['menus'][$menu_id]['nume_domeniu'] . "</a></li>";
}
if (isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='#'>" . $menu['menus'][$menu_id]['nume_domeniu'] . "</a>";
$html .= buildMenu($menu_id, $menu);
$html .= "</li>";
}
}
$html .= "</ul>";
}
return $html;
}
}
?>
Controller:
function afisare_domenii_tree() {
$this->load->model ( 'new_menu_model' );
$data['domains'] = $this->new_menu_model->buildMenu ();
$this->load->view('new_menu', $data);
}
View (using a bootstrap template):
<?php echo buildMenu(0, $menu);?>

function get_domains() {
$result = $this->db->get ( 'domenii' );
return $result;
You already returned from the function above, the code after it will not execute. This should have been more like
function get_domains() {
$result = $this->db->get ( 'domenii' );
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
while ($row = mysql_fetch_assoc($result)) {
//creates entry into menus array with current menu id ie. $menus['menus'][1]
$menu['menus'][$row['id_domeniu']] = $row;
//creates entry into parent_menus array. parent_menus array contains a list of all menus with children
$menu['parent_menus'][$row['parent']][] = $row['id_domeniu'];
}
return $menu;
}

I have updated your model. You cannot use mysql_ functions - Instead take a look at Codeigniter's Query Builder functions here ... http://www.codeigniter.com/userguide3/database/query_builder.html
<?php
class New_menu_model extends CI_Model {
function get_domains() {
$result = $this->db->get ( 'domenii' );
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
foreach($result->result_array() as $row)
{
//creates entry into menus array with current menu id ie. $menus['menus'][1]
$menu['menus'][$row['id_domeniu']] = $row;
//creates entry into parent_menus array. parent_menus array contains a list of all menus with children
$menu['parent_menus'][$row['parent']][] = $row['id_domeniu'];
}
return $menu;
}
function buildMenu($parent, $menu) {
$html = "";
if (isset($menu['parent_menus'][$parent])) {
$html .= "<ul>";
foreach ($menu['parent_menus'][$parent] as $menu_id) {
if (!isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='#'>" . $menu['menus'][$menu_id]['nume_domeniu'] . "</a></li>";
}
if (isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='#'>" . $menu['menus'][$menu_id]['nume_domeniu'] . "</a>";
$html .= $this->buildMenu($menu_id, $menu);
$html .= "</li>";
}
}
$html .= "</ul>";
}
return $html;
}
}
?>

Related

Magento diplaying category tree dynamically

I need to display my category tree as a list in a responsive menu.
The idea is to display the highest level categories. and create dynamically a list that will be displayed for each category that has children.
I stumbled upon a code that helped me a bit, but i can't figure how to get the job done.
Here is the code:
<?php
$rootCatId = Mage::app()->getStore()->getRootCategoryId();
function getTreeCategories($parentId, $isChild){
$allCats = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active','1')
->addAttributeToFilter('include_in_menu','1')
->addAttributeToFilter('parent_id',array('eq' => $parentId));
$class = ($isChild) ? "sub-cat-list" : "cat-list";
$html .= '<ul class="'.$class.'">';
$children = Mage::getModel('catalog/category')->getCategories(7);
foreach ($children as $category) {
{
$html .= '<li>'.$category->getName()."";
$subcats = $category->getChildren();
if($subcats != ''){
$html .= getTreeCategories($category->getId(), true);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
$catlistHtml = getTreeCategories($rootCatId, false);
echo $catlistHtml;
?>
Thank you in advance.
you can use this to create category tree:
<?php
$rootCatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootCatId);
$output= '<ul>';
foreach($categories as $category) {
$cat = Mage::getModel('catalog/category')->load($category->getId());
$count = $cat->getProductCount();
$output .= '<li>' . '' . $category->getName() . "";
if ($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$array .= get_categories($children);
}
$output .= '</li>';
}
echo $output . '</ul>';
?>
For the effects of showing / hiding categories and subcategories, you can use plain css or jQuery / Prototype.

PHP Use of undefined constant bigdata

The code is working rightly with the error:
Notice: Use of undefined constant bigdata - assumed 'bigdata' in
C:\xampp\htdocs\dynamic_menu\index.php on line 4
Code as followed:
//Set the database connection
($GLOBALS["___mysqli_ston"] = mysqli_connect('localhost', 'root', 'chethan'));
((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . 'bigdata'));
//select all rows from the main_menu table
$result = mysqli_query($GLOBALS["___mysqli_ston"], "select id,title,parentid,link from main_menu");
//create a multidimensional array to hold a list of menu and parent menu
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
//build the array lists with data from the menu table
while ($row = mysqli_fetch_assoc($result)) {
//creates entry into menus array with current menu id ie. $menus['menus'][1]
$menu['menus'][$row['id']] = $row;
//creates entry into parent_menus array. parent_menus array contains a list of all menus with children
$menu['parent_menus'][$row['parentid']][] = $row['id'];
}
// Create the main function to build milti-level menu. It is a recursive function.
function buildMenu($parent, $menu) {
$html = "";
if (isset($menu['parent_menus'][$parent])) {
$html .= "<ul>";
foreach ($menu['parent_menus'][$parent] as $menu_id) {
if (!isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='" . $menu['menus'][$menu_id]['link'] . "'>" . $menu['menus'][$menu_id]['title'] . "</a></li>";
}
if (isset($menu['parent_menus'][$menu_id])) {
$html .= "<li><a href='" . $menu['menus'][$menu_id]['link'] . "'>" . $menu['menus'][$menu_id]['title'] . "</a>";
$html .= buildMenu($menu_id, $menu);
$html .= "</li>";
}
}
$html .= "</ul>";
}
return $html;
}
select database like this
mysqli_select_db($GLOBALS["___mysqli_ston"], 'bigdata');
insted of this
((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . 'bigdata'));

How to loop an array in array (dynamic navigation)

I have an array with some items. Each array could have (or not) an subarray, also with some items.
How can I call the subarray in a loop? It is difficult to describe, here is the code. I know the code/syntax is not correct, but the syntax should clarify my problem:
<?php
$subitemsA = array(
'subA1' => array('num'=>65, 'text'=>'Labor', 'url'=>'#'),
'subA2' => array('num'=>44, 'text'=>'Rare', 'url'=>'#'),
);
$subitemsB = array(
'subB1' => array('num'=>0, 'text'=>'subB1', 'url'=>'#'),
'subB2' => array('num'=>0, 'text'=>'subB2', 'url'=>'#'),
'subB3' => array('num'=>0, 'text'=>'subB3', 'url'=>'#')
);
$navArray = array(
'Home' => array('num'=>0, 'text'=>'Home', 'url'=>'#'),
'Info' => array('num'=>0, 'text'=>'Info', 'url'=>'#', 'subArray'=>$subitemsA),
'Sport' => array('num'=>0, 'text'=>'Sport', 'url'=>'#', 'subArray'=>$subitemsB),
);
$html = '';
foreach($navArray as $item) {
$html .= "<li>";
$html .= "<a href='{$item['url']}'><i class='abc'></i>{$item['text']}</a>\n";
if (count($navArray) > 3) {
foreach($navArray.subArray as $subitem) {
$html .= "<li>";
$html .= "<a href='{$subitem['url']}'>{$subitem['text']}</a>\n";
$html .= "</li>";
}
}
$html .= "</li>";
}
The first foreach loop works. But how can I access the subArray of Info and Sport?
You need a three level foreach for this to work -
foreach($navArray as $key => $item) {
$html .= "<li>";
$html .= "<a href='{$item['url']}'><i class='abc'></i>{$item['text']}</a>\n";
foreach ($item as $itemkey => $value) {
if (is_array($value)) { //Now Check if $value is an array
foreach($value as $valuekey => $subitem) { //Loop through $value
$html .= "<li>";
$html .= "<a href='{$subitem['url']}'>{$subitem['text']}</a>\n";
$html .= "</li>";
}
}
}
$html .= "</li>";
}
This is an answer to your question in more general way: How to deal with multi-level nested array using recursion and template.
function parseArray(array $navArray, &$html, $depth = 0) {
foreach ($navArray as $item) {
$html .= "<li>";
// this function use template to create html
$html .= toHtml($item['url'], $item['text'], $depth);
foreach ($item as $subItem) {
if (is_array($subItem)) {
// use recursion to parse deeper level of subarray
parseArray($item, $html, $depth + 1);
}
}
$html .= "</li>";
}
}
function toHtml($url, $text, $depth)
{
$template = '';
if ($depth == 0) {
$template = '<a href=\'{{url}}\'><i class=\'abc\'></i>{{text}}</a>\n';
} elseif ($depth >= 1) {
$template = '<a href=\'{{url}}\'>{{text}}</a>\n';
}
// define more template for deeper level here if you want
$template = str_replace('{{url}}', $url, $template);
$template = str_replace('{{text}}', $text, $template);
return $template;
}
$html = '';
parseArray($navArray, $html);
Just hurrily forge this code out of mind, haven't test it yet. Hope it help.
Regards,

Php Multidimensional array for navigation

Needed Navigation Html
Home
Pages
About
Services
Products
Contact
FAQs
Sitemap
Privacy Policy
Column Layouts
1 Column
2 Column (Left Sidebar)
2 Column (Right Sidebar)
3 Column
4 Column
I want to use php arrays and foreach loops to output the needed html.
The php code I have thus far is:
<?php
$data = array("navigation");
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
$data['navigation']['Pages']['About'] = base_url('pages/about');
echo '<ul>';
foreach($data as $nav) {
foreach($nav as $subNavKey => $subNavHref) {
echo "<li><a href='$subNavHref'>$subNavKey</a>";
}
}
echo '</ul>';
?>
I was thinking I would need three foreach loops nested but php warnings/errors are generated when the third loop is reached on lines such as:
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
I'm not quite sure how to test for 3rd level depths such as:
$data['navigation']['Pages']['About'] = base_url('pages/about');
Also, outputting the needed li and ul tags in the proper positions has given me trouble aswell.
Use recursion
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
$data['navigation']['Pages']['About'] = base_url('pages/about');
$data['navigation']['Pages']['About']['Team'] = base_url('pages/team');
$data['navigation']['Pages']['About']['Team']['Nate'] = base_url('pages/nate');
echo "<ul>"
print_list($data);
echo "</ul>"
function print_list($menu) {
foreach($menu as $key=>$item) {
echo "<li>";
if(is_array($item)) {
echo "<ul>";
print_list($item);
echo "</ul>";
} else {
echo "<a href='{$val}'>$key</a>";
}
echo "</li>";
}
}
<?php
function nav($data) {
$html = '<ul>';
foreach ($data as $k => $v) {
if (is_array($v)) {
$html .= "<li>$k" . nav($v) . "</li>";
}
else {
$html .= "<li><a href='$k'>$v</a>";
}
}
$html .= '</ul>';
return $html;
}
echo nav($data);
A recursive function can get the job done:
$items = array(
"Home",
"Pages" => array(
"About",
"Services",
"Products",
"Contact",
"FAQs",
"Sitemap",
"Privacy Policy",
"Column Layouts" => array(
"1 Column",
"2 Column (Left Sidebar)",
"2 Column (Right Sidebar)",
"3 Column",
"4 Column"
)
)
);
function getMenu($array) {
foreach($array as $key => $value) {
if(is_array($value)) {
echo "<li>" . $key . "</li>";
echo "<ul>";
getMenu($value);
echo "</ul>";
} else {
echo "<li>" . $value . "</li>";
}
}
}
echo "<ul>";
getMenu($items);
echo "</ul>";
Output:
You should use a recursive function, for example (Working Demo):
function makeMenu($array)
{
$menu = '';
foreach($array as $key => $value) {
if(is_array($value)) {
$menu .= '<li>' . $key . '<ul>' . makeMenu($value) . '</ul></li>';
}
else {
$menu .= "<li><a href='". $value ."'>" . $value ."</a></li>";
}
}
return $menu;
}
Then call it like:
$data = array(
"Home",
"Pages" => array("About", "Services"),
"Column Layouts" => array("1 Column", "2 Column (Left Sidebar)")
);
echo '<ul>' . makeMenu($data) . '</ul>';

dynamic custom menu php

trying to get some thing like that dynamically
<ul>
<li>Home</li>
<li>About Us</li>
<li>Academics
<ul style="overflow: hidden; display: block; height: 0px; z-index: 51; opacity: 0.00980392;">
<li>Bs Computer Science</li>
<li>Diplomas (DIT & DCHE)</li>
<li>MBAIT</li>
</ul>
</li>
<li><a class=" " href="#">College</a>
</ul>
the code is
<?php
//========================================================
$result = mysql_query(" SELECT id, parentId, name
FROM
menu
ORDER BY
parentId, name");
$menuData = array(
'items' => array(),
'parents' => array()
);
while ($menuItem = mysql_fetch_assoc($result))
{
$menuData['items'][$menuItem['id']] = $menuItem;
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
}
function buildMenu($parentId, $menuData)
{
$html = '';
if (isset($menuData['parents'][$parentId]))
{
$html = '<ul id="main_menu">';
foreach ($menuData['parents'][$parentId] as $itemId)
{
$html .= '<li>' . $menuData['items'][$itemId]['name'];
// find childitems recursively
$html .= buildMenu($itemId, $menuData);
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
//=======================================================
?>
above code is showing only first parents elements in the menu and the remaing elements are not showing.. the menu is not working correctly becoz of the class id is not given in the ul tag.. and by writing this
echo '<ul id="main_menu">';
// output the menu
echo buildMenu(0, $menuData);
echo "</ul>";
it shows nothing in the menu
Ok, try this:
<?php
//========================================================
$result = mysql_query(" SELECT id, parentId, name, link
FROM
menu
ORDER BY
parentId, name");
$menuData = array(
'items' => array(),
'parents' => array()
);
while ($menuItem = mysql_fetch_assoc($result)) {
$menuData['items'][$menuItem['id']] = $menuItem;
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
}
function buildMenu($parentId, $menuData)
{
$html = '';
if (isset($menuData['parents'][$parentId]) && count( $menuData['parents'][$parentId] ) > 0 ) {
if( $parentId == "0" ){
$html = '<ul id="main_menu">';
}else{
$html = '<ul id="sub_menu">';
}
foreach ($menuData['parents'][$parentId] as $itemId) {
$html .= '<li>';
$html .= strlen($menuData['items'][$itemId]['link']) > 2?
''.$menuData['items'][$itemId]['name'].'':
$menuData['items'][$itemId]['name'];
$html .= buildMenu($itemId, $menuData);
$html .= "</li>";
}
$html .= '</ul>';
} else {
$html .= '<li>' . $menuData['items'][$parentId]['name'].'</li>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
//=======================================================
?>

Categories