Well, I am writing a web service using PHP to return data from a DB in JSON format. I need to query 3 tables, which have a one-to-many relationship, like shown below:Contact Group ---(has)---> Contact ---(has)---> Phone numberHere I want to get an array of each group, in each group, get an array of all contacts and in each contact, get an array of all phone numbers. Because I am new to PHP, this might not be following best practices for PHP. The code I wrote is below:$sql = SELECT r.contact_id, contact_name, group_id, group_name, phone_id, phone_number FROM contact r LEFT JOIN contact_group s ON r.contact_group = s.group_id LEFT JOIN phone_numbers t ON r.contact_id = t.contact_id ORDER BY group_id, contact_id, phone_id;$query = mysqli_query($conn,$sql);$data = array();while ($row = mysqli_fetch_array($query)) {    $data[$row[group_id]][group_id] = $row[group_id];    $data[$row[group_id]][group_name] = $row[group_name];    $data[$row[group_id]][contacts][$row[contact_id]][id] = $row[contact_id];    $data[$row[group_id]][contacts][$row[contact_id]][name] = $row[contact_name];    $data[$row[group_id]][contacts][$row[contact_id]][phone_number][$row[phone_id]][id] = $row[phone_id];    $data[$row[group_id]][contacts][$row[contact_id]][phone_number][$row[phone_id]][number] = $row[phone_number];}I think my code is very ugly and seems difficult to read. Could you help me review my code and refactor it to make it more beautiful or introduce new ways to solve that problem?
PHP handle array when query database with one-to-many relationship
php;array;php5;mysqli