The purpose of this code is to get data from the database and output it into a multidimensional array in JSON for my web app. But my gut instinct is telling me this code is way too messy and just generally badly written.// Structure of user_medication http://i.imgur.com/gTrZm7B.pngpublic function getUserMedication($data, $success, $fail){        Permission::required(1, function() use($data, $success, $fail){                $user = $data[user];                if(!$this->isUserUIDValid($user)){                        $fail([detail=>user does not exist!]); return;                }                $medicationDates = $this->database->rowQuery(SELECT * FROM (SELECT *, id AS date_id FROM user_medication_dates WHERE user_uid = ? ORDER BY date DESC LIMIT 2) AS umd LEFT JOIN user_medication AS um ON umd.date = um.date ORDER BY umd.date DESC, array($data[user]));                $processedMedications = [];                foreach ($medicationDates as $key => $value) {                        if(!isset($processedMedications[$value[date_id]])){                                $processedMedications[$value[date_id]][date] = $value[date];                        } elseif(!isset($processedMedications[$value[date_id]][$value[time]])){                                $processedMedications[$value[date_id]][$value[time]] = [];                        }                        $processedMedications[$value[date_id]][$value[time]][] = $value;                }                $success($processedMedications);        });}/* The output in JSON;{     status:success,   data:{        96:{           date:2015-05-30,         am:[              {                 id:90,               date:2015-05-30,               user_uid:553669eea746d,               date_id:96,               medication:test,               dose:1,               quantity:2,               time:AM            }         ],         pm:[              {                 id:91,               date:2015-05-30,               user_uid:553669eea746d,               date_id:96,               medication:another,               dose:1,               quantity:2,               time:PM            }         ]      }   }}*/
Processing database data into a multidimensional array
php;mysql