I have some hierarchical data, created its thus:
CREATE TABLE `departments`
(`deperatment_id` INTEGER NOT NULL,
`department_name` varchar(32) NOT NULL);
INSERT INTO `departments`(`deperatment_id`, `department_name`)
VALUES (1, "HR"), (2, "Software"), (3, "Accounts");
CREATE TABLE `jobs` (`deperatment_id` INTEGER NOT NULL,
`job_id` INTEGER NOT NULL,
`job_name` varchar(32) NOT NULL);
INSERT INTO `jobs` (`deperatment_id`, `job_id`, `job_name`)
VALUES (1, 1, "Idiot"),
(1, 2, "Fool"),
(2, 3, "PHB"),
(2, 4, "Software guru"),
(2, 5, "PFY"),
(3, 6, "Number cruncher");
CREATE TABLE `peeps` (`job_id` INTEGER NOT NULL,
`peep_name` varchar(32) NOT NULL);
INSERT INTO `peeps`(`job_id` , `peep_name` )
VALUES(1, "Smith"),
(2, "Jones Major"),
(2, "Jones Minor"),
(4, "Mr. In-the-wrong-department"),
(4, "Mawg"),
(5, "William Topaz McGonagall"),
(6, "Blaise Pascal"),
(6, "Isaac Newton");
So, as you can see, there can be one or more departments, each of which can have one or more jobs, done by one or more people.
It's a neat tree hierarchy and I want to return it in response to an AJAX request, so I have three nested for loops, each issuing a SELECT
statement (coed unavailable, as it is at home & I am in the office, but I am sure that you can visualize it; it's straightforward enough).
I was having some problems client side, trying to add a new, blank entry, and it was suggested that I should be retiring an array of objects, as shown here.
However, that shows only on level of depth, so a single SELECT
with while ($row = $stmt->fetch(PDO::FETCH_OBJ))
was enough to build the return value - an array of objects.
How do I build my return value, which will be a nested array of array of arrays of objects?
[Update] I have removed the previous reference to a fiddle, as it confused at least one person.
I want to return an array of departments, each containing data for that department, plus an array of jobs, each containing data for that job, plus an array of people who perform that job
[Update] Here's an easy 50 points for someone.
@YeldarKurmangaliyev 's answer is 90% complete, but I just need some enlightenment on two small points.
his SQL doesn't show the data associated with
departments
. I suspect that I just need to(INNER?) JOIN departments.*
. But what is the exact SQL command?what's the PHP code? I suspect
$result = $sqlQuery->fetchAll(PDO::FETCH_ASSOC);
or similar
Btw, there's a fiddle for the SQL
My best efforts only return a flat array, not a nested tree as the posted answer shows :-(
[Update] Thanks for the great answer. In order to help others, I have posted a working fiddle at http://phpfiddle.org/main/code/xfdj-wthc
Note that the solution supports multiple foreign keys, where I only have one. I could simplify the code for personal use, but thank @trincot for making it so flexible as this might be of use to others.