Для начала правильно спроектировать таблицы:
create table class (
id int primary key auto_increment,
name varchar(64) unique key
);
create table subclass (
id int primary key auto_increment,
class_id int references class(id),
name varchar(64) unique key
);
create table items (
id int primary key auto_increment,
subclass_id int references subclass(id),
name varchar(64) unique key
);
insert into class (name) values ('Fruits'), ('Vegetables');
insert into subclass (class_id, name) values (1, 'Red'), (1, 'Orange'), (2, 'Green'), (2, 'Yellow');
insert into items (subclass_id, name) values
(1, 'Apple'), (2, 'Pineapple'), (3, 'Cucumber'), (3, 'Carrot');
Затем написать код PHP:
<?php
$query = 'select class.name class, subclass.name subclass, items.name item
from items
join subclass on items.subclass_id = subclass.id
join class on subclass.class_id = class.id;';
// get DB version using PDO
$stmt = $pdo->prepare($query);
$stmt->execute();
$res = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (!isset($res[$row["class"]])) {
$res[$row["class"]] = [];
}
if (!isset($res[$row["class"]][$row["subclass"]])) {
$res[$row["class"]][$row["subclass"]] = [];
}
$res[$row["class"]][$row["subclass"]][] = $row["item"];
}
print_r(json_encode($res, JSON_PRETTY_PRINT));
Проверить код
PHP online