php - How to calculate rows in foreach loop recursive?
Get the solution ↓↓↓This code below returns category tree.
How can I get the count of the products in each category that has sub categories? I mean to sum values in each subcategory.
Until now I succeed to get the count only for the last level of child category:
function menuList($data, $parent = 0 ){
static $i = 1;
$tab = str_repeat(' ',$i);
if($data[$parent]){
$html = $tab.'<ul id="menu'.$i.'">';
$i++;
$count=0;
foreach($data[$parent] as $v){
$id = $v->id;
$categoryname=$v->bg_category;
if(in_array($id, $_SESSION['active_product_categories'])){
$q='select distinct product_id from products_to_categories where category_id="'.$id.'"';
$res=mysql_query($q) or die());
$num_rows=mysql_num_rows($res);
$count='( '.$num_rows.' )';
}
$child = menuList($data, $v->id);
$html .= $tab.'<li>';
$html .= '<a href="'.$v->WebSite.'/shop/index.php?offers='.$id.'">'.$categoryname.' '.$count.' </a>';
if($child){
$i–;
$html .= $child;
$html .= $tab;
}
$html .= '</li>';
}
$html .= $tab.'</ul>';
return $html;
} else {
return false;
}
}
$query = mysql_query('select * from products_categories where visible="1" group by bg_category order by bg_category ASC');
while($r=mysql_fetch_object($query)){
$data[$r->parent][] = $r;
}
$menu = menuList($data);
echo $menu;
Please have a look at the screenshot.
Here is the screenshot: http://tinypic.com/view.php?pic=zwgvoz&s=8#.U957sizlrDc
Answer
Solution:
Well, I don't know your table's structure, but why don't you fix it in SQL:
$q = 'SELECT parent_id, parent_name, count(child_id) FROM your_table GROUP BY parent_id';
And only then build up your HTML view. This code is extremely approximate.
Answer
Solution:
If I were you, I would try to write two classes, below I've added examples in pseudo code:
Class Menu
{
private $aSubMenus
public function __construct()
public function getNumberOfItems()
public function addMenuItem()
public function getHTML()
public function load($menuID)
}
Class MenuItem
{
public function __construct()
public function getHTML()
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the payload is invalid.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.