I have three mysql tables: clients, cars and insurance. Each client can have multiple cars and each car cand have multiple insurance policies. Here's my query and a link to sqlfiddle:
SELECT
a.*,
b.id AS car_id, b.license_number, b.brand, b.model,
c.id AS insurance_id, c.insurance_company, c.start_date, c.end_date, c.price
FROM clients a
LEFT JOIN cars b ON a.id = b.client_id
LEFT JOIN insurance c ON b.id = c.car_id
http://sqlfiddle.com/#!2/773a5/1
So for two clients where the first client has two cars and three insurance policies and the second one has no car and no insurance, the query will return 4 rows.
What I can't figure out is how to loop this query in order to return the following structure, while avoiding duplicate client entries.
Array
(
[0] => Array
(
[id] => 1
[first_name] => John
[last_name] => Smith
[cars] => Array
(
[id] => 1
[license_number] => 'plate1'
[brand] => 'BMW'
[model] => 'E35'
[insurance] => Array
(
[id] => 1
[start_date] => '2015-02-10'
[end_date] => '2016-02-10'
[price] => '100'
)
(
[id] => 2
[start_date] => '2014-02-10'
[end_date] => '2015-02-10'
[price] => '50'
)
)
(
[id] => 2
[license_number] => 'plate2'
[brand] => 'VW'
[model] => 'Golf'
[insurance] => Array
(
[id] => 3
[start_date] => '2015-02-10'
[end_date] => '2016-02-10'
[price] => '100'
)
)
)
[1] => Array
(
[id] => 1
[first_name] => John
[last_name] => Smith
[cars] => NULL
)
)