Suppose i have the following tables :
- projects( project_id , project_name )
- documents( document_id,document_name
, project_id)
which is kind of top-down hierarchically , i use select statement and loops to generate nested array ex.:
$result_array = array();
$projects = mysql_query(' SELECT * FROM projets') ;
$i = 0 ;
while( $row_proj = mysql_fetch_assoc($projects) )
{
$result_array[$i] = $row_proj ;
$documents = mysql_query('SELECT * FROM documents WHERE project_id='.$row['project_id']);
$doc_res = array();
while( $row_doc = mysql_fetch_assoc($documents)
{
$doc_res[] = $row_doc;
}
$result_array[$i]['documents'] = $row_doc ;
$i++;
}
.. and so on
the result is nesteed array so in view i can print it like :
foreach( $projects as $project )
{
echo $project['project_name'];
foreach( $project['documents'] as $document )
{
echo ..
}
}
how i can generate this using simple flat loop using SQL statment or any other thing , this way seem not the best one , sometimes i use join but its not generate things like nested array .
If I understand the thing you want to achieve I would do:
Then iterate through all of the documents to group them in arrays by project_id with PHP. You will have one query again. It is possible to do MySQL loop but would rather by an ugly thing to do and for the above example it won’t give you any advantage.