I created a mySQL database with phpMyAdmin in my local server. In this database I store the names and the favourite NBA teams of my friends.This is obviously a many-to-many relationship. For this reason, I run the followed script in MySQL to create the appropriate tables for this database:
CREATE TABLE `friends` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `teams` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `relations` (
`friends_id` int(4) NOT NULL,
`teams_id` int(4) NOT NULL,
`status` varchar(30) NOT NULL
);
Obviously, I inserted some values to these tables but I do not provide extensively the source code here so as to save some space. An small piece of it is the following:
INSERT INTO `friends` (`id`, `name`)
VALUES
(1,'David Belton'),
(2,'Alex James');
INSERT INTO `teams` (`id`, `name`)
VALUES
(1,'Cleveland Cavaliers'),
(2,'Boston Celtics'),
(3,'Houston Rockets');
INSERT INTO `relations` (`friends_id`, `teams_id`, `status`)
VALUES
(1,1, 'Current'),
(2,1, 'Current'),
(2,2, 'Past'),
(2,3, 'Past');
After running a PHP script that fetches the data from the database and print them, I want to have the following kind of valid json output for each of my friends:
{
"id": "1",
"name": "Alex James",
"Current team": ["Boston Celtics"]
"Past team": [ "Cleveland Cavaliers", "Houston Rockets"]
}
How can I make this array of favourite teams for each person with MySQL?
P.S. My current question is inspired by the following answered question: How to join arrays with MySQL from 3 tables of many-to-many relationship