How to process data with a one to many relation from MySQL into PHP -


i using following query return data single habit.

a habit can have many steps , many comments.

when run following query repeats data habit every step , comment there is.

        select          habit_id, habit_user_id, habit_name, habit_category_id, habit_description, habit_target_user, habit_up_votes, habit_down_votes,          step_id, step_description,          comment_id, comment_user_id, comment_description         habits, steps, comments          habit_id = ?          , habit_id = step_habit_id         , habit_id = comment_habit_id         order step_order 

example output (the ids should enough idea of going on):

habit_id    step_id    step_description    comment_id    comment_description 1           1          x                1             works great! 1           1          x                2             awful! 1           1          x                3             nice job 1           2          y           1             works great! 1           2          y           2             awful! 1           2          y           3             nice job 

i want able take returned data , have in 1 array.

array("habit_id" => 1, "step_id" => array(1, 2), "comment_id" => array(1, 2, 3)); 

the ways can think of doing either:

executing 3 seperate queries 1 habit data, 1 steps habit , 1 comments habit.

or

by using above query , constructing new array habit data , looping through rows , constructing new array steps , comments while @ same time making sure there no duplicates added.

this sounds way inefficient, can suggest better way either modifying query provide php more workable data or trick in php. did @ 1 point consider concatenating data arrays steps , comments within query, thought should php's job manipulate data in such way.

the reason why want data in way return used in angularjs application.

the query fine is. it's returning enough data iterate through , build array want.

$data = array();  // type of loop here. whatever returns data query while($row=mysql_fetch_array($result)) {     $data['habit_id'] = $row['habit_id'];      // in_array check ensures there no dupes     if (!in_array($row['step_id'], $data['step_id'])) {         $data['step_id'][] = $row['step_id'];     }     if (!in_array($row['comment_id'], $data['comment_id'])) {         $data['comment_id'][] = $row['comment_id'];     } } 

this going more efficient 3 separate queries. make sure database indexed. , check you're using indexes running query explain.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -