I keep getting the following warning listed below on line 3.
Warning: Invalid argument supplied for foreach()
Here is the php code.
function dyn_menu($parent_array, $sub_array, $qs_val = "menu", $main_id = "nav", $sub_id = "subnav", $extra_style = "foldout") {
$menu = "<ul id=\"".$main_id."\">\n";
foreach ($parent_array as $pkey => $pval) {
if (!empty($pval['count'])) {
$menu .= " <li><a class=\"".$extra_style."\" href=\"".$pval['link']."?".$qs_val."=".$pkey."\">".$pval['label']."</a></li>\n";
} else {
$menu .= " <li>".$pval['label']."</li>\n";
}
if (!empty($_REQUEST[$qs_val])) {
$menu .= "<ul id=\"".$sub_id."\">\n";
foreach ($sub_array as $sval) {
if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) {
$menu .= "<li>".$sval['label']."</li>\n";
}
}
$menu .= "</ul>\n";
}
}
$menu .= "</ul>\n";
return $menu;
}
Here is the whole code I'm working on.
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT id, label, link_url, parent_id FROM dyn_menu ORDER BY parent_id, id ASC");
if (!$dbc) {
// There was an error...do something about it here...
print mysqli_error();
}
while ($obj = mysqli_fetch_assoc($dbc)) {
if (empty($obj['parent_id'])) {
echo $parent_menu . $obj['id']['label'] = $obj['label'];
echo $parent_menu . $obj['id']['link'] = $obj['link_url'];
} else {
echo $sub_menu . $obj['id']['parent'] = $obj['parent_id'];
echo $sub_menu . $obj['id']['label'] = $obj['label'];
echo $sub_menu . $obj['id']['link'] = $obj['link_url'];
echo $parent_menu . $obj['parent_id']++;
}
}
mysqli_free_result($dbc);
function dyn_menu($parent_array, $sub_array, $qs_val = "menu", $main_id = "nav", $sub_id = "subnav", $extra_style = "foldout") {
$menu = "<ul id=\"".$main_id."\">\n";
foreach ($parent_array as $pkey => $pval) {
if (!empty($pval['count'])) {
$menu .= " <li><a class=\"".$extra_style."\" href=\"".$pval['link']."?".$qs_val."=".$pkey."\">".$pval['label']."</a></li>\n";
} else {
$menu .= " <li>".$pval['label']."</li>\n";
}
if (!empty($_REQUEST[$qs_val])) {
$menu .= "<ul id=\"".$sub_id."\">\n";
foreach ($sub_array as $sval) {
if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) {
$menu .= "<li>".$sval['label']."</li>\n";
}
}
$menu .= "</ul>\n";
}
}
$menu .= "</ul>\n";
return $menu;
}
function rebuild_link($link, $parent_var, $parent_val) {
$link_parts = explode("?", $link);
$base_var = "?".$parent_var."=".$parent_val;
if (!empty($link_parts[1])) {
$link_parts[1] = str_replace("&", "##", $link_parts[1]);
$parts = explode("##", $link_parts[1]);
$newParts = array();
foreach ($parts as $val) {
$val_parts = explode("=", $val);
if ($val_parts[0] != $parent_var) {
array_push($newParts, $val);
}
}
if (count($newParts) != 0) {
$qs = "&".implode("&", $newParts);
}
return $link_parts[0].$base_var.$qs;
} else {
return $link_parts[0].$base_var;
}
}
echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav");
It's telling you that $parent_array isn't an array.
If you post the code that calls this function, we can tell you more.
Are you sure $parent_array is actually an array? Try checking it with is_array first (perhaps returning an empty string to represent the menu or whatever - adapt to your needs):
if (!is_array($parent_array)) {
return "";
}
This error happens when you supply not an array into forearch. Try print_r() first argument of every foreach
If you change your function signature to include type hinting (only works for arrays and objects), you'll be sure that your function gets what it needs:
function dyn_menu(array $parent_array, array $sub_array, //etc.)
And you should get an error message that pinpoints the caller of the function, which is where the problem really is.
It looks like you were expecting to build $parent_array in that while loop at the beginning. Instead it's just echoing stuff.
The lines like:
echo $parent_menu . $obj['id']['label'] = $obj['label'];
Should probably be like:
$menu['label'] = $obj['label'];
Then at the end (inside) of the loop add something like:
$parent_menu[$obj['id']] = $menu;
So you build the array you're using in dyn_menu.
In any case, the while loop looks like your problem. It's not building $parent_menu from the data.
Related
I would to create a recursive function in order to retrieve data from an array and to organize then.
However I have some difficulties to create the right logic. The principle must be apply to any sub level until it ends or nothing is found.
I want to prevent this kind of code by repeating a foreach inside a foreach...:
$cats = get_categories($args);
$categories = array();
foreach($cats as $cat){
$parent = $cat->category_parent;
if ($parent) {
$categories['child'][$parent][$cat->cat_ID] = $cat->name;
} else {
$categories['parent'][$cat->cat_ID] = $cat->name;
}
}
}
if (isset($categories['parent']) && !empty($categories['parent'])) {
foreach($categories['parent'] as $id => $cat){
$new_cats[$id]['title'] = $cat;
if (isset($categories['child'][$id])) {
foreach($categories['child'][$id] as $child_id => $child_cat){
$new_cats[$child_id]['title'] = $child_cat;
$new_cats[$child_id]['parent_id'] = $id;
if (isset($categories['child'][$child_id])) {
foreach($categories['child'][$child_id] as $sub_child_id => $sub_child_cat){
$new_cats[$sub_child_id]['title'] = $sub_child_cat;
$new_cats[$sub_child_id]['parent_id'] = $child_id;
}
}
}
}
}
}
}
May be this code help you to get idea for formatting your desired array format.
<?php
// Main function
function BuildArr($arr)
{
$formattedArr = array();
if(!empty($arr))
{
foreach($arr as $val)
{
if($val['has_children'])
{
$returnArr = SubBuildArr($val['children']); // call recursive function
if(!empty($rs))
{
$formattedArr[] = $returnArr;
}
}
else
{
$formattedArr[] = $val;
}
}
}
return $formattedArr;
}
// Recursive Function( Build child )
function SubBuildArr($arr)
{
$sub_fortmattedArr = array();
if(!empty($arr))
{
foreach($arr as $val)
{
if($val['has_children'])
{
$response = SubBuildArr($val['children']); // call recursive
if(!empty($response))
{
$sub_fortmattedArr[] = $response;
}
}
else
{
$sub_fortmattedArr[] = $arr;
}
}
return $sub_fortmattedArr;
}
}
?>
I use this code for my previous project for generating categories that upto n-th level
Here I have my database table and my table name is category where I store my data category and subcategory in category column
i want to fetch this data like this format in ul li for this code i have trying to arrange but i am not fetch data perfectly like this please help me to arrange my code this format.
You can try like this
//to select categories
$this ->db-> select();
$this->db->from('category');
$this->db->where('pid',0);
$query = $this->db->get();
$categories = array();
$i=0;
foreach ($query->result_array() as $row) {
//put all category names to $categories array
$categories[$i] =$row['category'];
$i++;
}
//to select relevant sub categories
$sub_categories=array();
foreach ($categories as $category) {
$this ->db-> select();
$this->db->from('category');
$this->db->like('category', $category, 'after');
$query = $this->db->get();
$j=0;
foreach ($query->result_array() as $row) {
//put all sub categories names to $sub_categories array
$sub_categories[$category][$j] =$row['category'];
$j++;
}
}
$return_data['categories']=$categories;
$return_data['sub_categories']=$sub_categories;
return $return_data;
This code is useful for get nth level of category,subcategory array
controller:
$this->load->model('getmenu_model');
function get_menu() {
$ci = & get_instance();
$ci->load->model("getmenu_model");
$menu['menu'] = $ci->getmenu_model->get_menu();
$echo = echoMenu($menu['menu']);
//$echo.= "<li>Loose Diamonds</li>";
$menu['print_menu']=$echo;
print_r($menu);
//return $menu;
}
function echoMenu($arr) {
$ci = & get_instance();
$echo = "";
//$echo.="<ul>";
foreach ($arr as $subArr) {
if (!empty($subArr['sub_menu'])) {
$echo.= "<li>";
$echo.= "" . $subArr['name'] . "";
if ($subArr['sub_menu']) {
$echo.= "<ul>";
$echo .=echoMenu($subArr['sub_menu']);
$echo.= "</ul>";
}
$echo.= "</li>";
} else {
$echo.= "<li>" . $subArr['name'] . "</li>";
}
}
//$echo.= "</ul>";
return $echo;
}
model:
public function get_menu() {
$this->db->select('id,name,parent_id');
$menu = $this->db->get('category')->result_array();
$data=$this->menu_child($menu);
//print_r($data);
return $data;
}
function menu_child($menu, $parent = NULL) {
// echo $parent."---";
$main_menu = array_filter($menu, function($a)use($parent) {
return $a['parent_id'] == $parent;
});
// print_r($main_menu);
if ($main_menu) {
foreach ($main_menu as $key => $value) {
$main_menu[$key]['sub_menu'] = $this->menu_child($menu, $value['id']);
}
}
// print_r($main_menu);
return $main_menu;
}
i try to make an simple way to create an box in a class.
The problem is , it only give me the first element in the array. I echo out the $values and i get the whole css code and i try to place them in style at div. But still get only the last element.
My currently code looks like:
class general {
public function box($content,$style,$width = 50,$height = 50) {
foreach ($style as $k => $v) {
$values = ''.$k.':'.$v.';';
echo($values);
$box = '<div class="testBox" style="'.$values.'">'.$content.'</div> ';
}
return $box;
}
}
$general = new general();
$test = array(
'background-color' => '#000',
'font-size' => '120px'
);
echo $general->box('testValue',$test);
Try like this:
public function box($content,$style,$width = 50,$height = 50) {
$values = '';
foreach ($style as $k => $v) {
$values .= ''.$k.':'.$v.';';
}
$box = '<div class="testBox" style="'.$values.'">'.$content.'</div> ';
return $box;
}
$box = '<div class="testBox" style="'.$values.'">'.$content.'</div> ';
to
$box .= '<div class="testBox" style="'.$values.'">'.$content.'</div> ';
And declare
$box = ''; outside the loop.
You need to concate the data using .
I have been searching around for some time but cannot seem to find an answer to my problem.
I have a deep nested array that I need to turn into a nested menu.
https://gist.github.com/anonymous/98e0dcf4f2aef40a1da6
I would like it to end up as something like the following.
https://gist.github.com/anonymous/a0dd4c7d047f11a5ce82
class foo {
function NavigationBuild($routes, $child = false) {
if ($child) {
foreach($routes as $route = > $row) {
if (is_array($row['children'])) {
$output. = self::NavigationBuild($row['children'], true);
} else {
$output. = "<li>".$val['route']."MEEEEE</li>";
}
}
} else {
$output. = '<ul>';
foreach($routes as $route = > $row) {
if (!strlen($row['parent'])) {
$output. = "<li>".$route."</li>";
}
foreach($row['children'] as $key = > $val) {
if (is_array($val['children'])) {
$output. = self::NavigationBuild($val['children'], true);
} else {
$output. = "<li>".$val['route']."MEEEEE</li>";
}
}
}
$output. = '</ul>';
}
return $output;
}
}
Figured it out - seems some sleep was needed.
Thanks to all USEFUL input
I have made function to get multidemnsional menu from database.
public function get_menu($parent=0,$vis=1) {
$categories = array();
$this->db->from('ci_categories');
$this->db->where('cat_child',$parent);
$this->db->where('cat_vis',1);
$this->db->order_by('cat_order');
$q = $this->db->get();
$result = $q->result();
$i=0;
foreach($result as $mainCategory) {
$mainCategory->cat_subcategories = $this->get_menu($mainCategory->cat_id);
$categories[$i] = $mainCategory;
$i++;
}
return $categories;
}
It is working but I would like to print out the menus. For now I can print main menu and one child with this code:
if (count($menu) > 0) {
foreach($menu as $menu_item) {
$link = anchor("category/".$menu_item->cat_url, $menu_item->cat_name);
echo "<li>$link";
if (!empty($menu_item->cat_subcategories)) {
echo "<ul>";
foreach($menu_item->cat_subcategories as $subcat) {
$sub_link = anchor("category/".$subcat->cat_url, $subcat->cat_name);
echo "<li>$sub_link</li>";
}
echo "</ul>";
}
echo "</li>";
}
}
It is working too but how could I print out even 3rd or 4th submenu without manualy writing those foreach and ifs ? Thanks
You can try a recursive function...
Something like:
function showMenu($menu) {
echo "<ul>";
foreach ($menu as $menu_item) {
$link = anchor("category/".$menu_item->cat_url, $menu_item->cat_name);
echo "<li>$link";
if (!empty($menu_item->cat_subcategories)) showMenu($menu_item->cat_subcategories);
echo "</li>";
}
echo "</ul>";
}
That's an idea ;)