PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
create table prod_category ( id int auto_increment primary key, name varchar(32), parent_category int ); insert into prod_category (name, parent_category) values ('cat1', 0),('cat2', 1),('cat3', 1),('cat4', 3),('cat5', 3), ('cat6', 0),('cat7', 6),('cat8', 0),('cat9', 8),('cat10', 9); create table products ( id int auto_increment primary key, name varchar(32), category_id int ); insert into products (name, category_id) values ('prod2', 1), ('prod3', 2), ('prod4', 3), ('prod5', 4), ('prod6', 5), ('prod7', 6), ('prod8', 7), ('prod9', 8), ('prod10', 9);
Copy Clear
Copy Format Clear
<?php // get categoriies into array >>> $sth = $pdo->prepare("select * from prod_category"); $sth->execute(); $result = $sth->fetchAll(PDO::FETCH_ASSOC); $categories = []; foreach ($result as $c) { $categories[$c['id']] = $c; }; // <<< get categoriies into array // recursive function get product main category function get_main_category($cat) { global $categories; return $categories[$cat]['parent_category'] == 0 ? $categories[$cat]['name'] : get_main_category($categories[$cat]['parent_category']); } $sth = $pdo->prepare("select * from products"); $sth->execute(); $result = []; while ($prod = $sth->fetch(PDO::FETCH_ASSOC)) { $prod['main_category'] = get_main_category($prod['category_id']); if (isset($res[$prod['main_category']])) $res[$prod['main_category']]++; else $res[$prod['main_category']] = 1; } print_r($res);
Show:  
Copy Clear