Nested SQL loop with PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • blyxx86
    Contributor
    • Nov 2006
    • 258

    #1

    Nested SQL loop with PHP

    Good morning,

    I am trying to improve the efficiency of this code, I'm not sure if it can be done.

    The requirement is that I use two SQL statements that I pass into two ($result, $result2) resources. I need data from SQL1 to be displayed only once, but the data in SQL2 is related 1:n and I am printing out those second records in a table within the original table.

    SQL1 usually returns about 30-100 results.
    SQL2 returns about 3-10 results per SQL1 result (so 90-1000 records).

    Code:
    $index = array();
    while($row = good_assoc($result))
    {
    	$index[$row['Service_id']] = array('data'=>$row, 'notes' => array());
    }
    
    while($row=good_assoc($result2))
    {
    	if(isset($index[$row['Service_id']]))
    	{
    		$index[$row['Service_id']]['notes'][]=$row;
    	}
    }
    I then loop through the $index array
    Code:
    echo ("\r\n\t<table>");
    foreach ($index as $id => $call)
    {
    	echo("\r\n\t\t<tr class='d1'>");
    	echo ("\r\n\t\t\t<td>{$call['data']['Service_id']}</td>");
    	echo ("\r\n\t\t\t<td>");
    	if(isset($call['notes'][0])) //Check to see if we even need to loop through for notes.
    	{
    		echo ("\r\n\t\t<table>");
    		foreach($call['notes'] as $call)
    		{
    			echo ("\r\n\t\t\t<tr class=\"note\">");
    			echo ("\r\n\t\t\t\t<td>{$call['Note']}</td>");
    			echo ("\r\n\t\t\t</tr>");
    		}
    		echo ("\r\n\t\t<\table>");
    	}
    	echo ("\r\n\t\t\t<\td>
    	echo("\r\n\t\t<\tr>");
    }
    echo ("\r\n\t<\table>");

    Also, I would like to turn this into a function if possible... How/Where would I start? I've made simple functions in the past, but this one seems scarier. This is only a secondary question, my first concern is speeding up the process here.

    Thanks!
Working...