Page is a not externally linkable
- Code, Content, and Presentation
-- PHP Server Side Scripting
---- Creating Multidimentional Array From SQL Statement


rocknbil - 4:35 pm on Jun 27, 2012 (gmt 0)


I wouldn't do an array. Arrays need to be stored in memory, and the more memory you use, the slower things get. Additionally, once you construct your arrays, you'll have to do all your sorting and output in programming, and you can leverage the power of mySQL to make your job a lot easier.

I would do some sort of toggle so it will only output a "new name" if the name value has changed. For example, simplifying so you can see the concept,


$rows=$currName=null;
while (list($name,$event,$date) = mysql_fetch_array($result)) {
if ($name==$currName) { $displayName=' '; }
else { $displayName=$currName=$name; }
$rows .= "
<tr>
<td>$displayName</td>
<td>$event</td>
<td>$date</td>
</tr>
";
}
if ($rows) { echo "<table>$rows</table>"; }
else { echo "<p>No results were found.</p>"; }


Some notes:

- as always, not working code typed on the fly for example only.

- This
$rows=$currName=null;
1) is just good programming (always initialize any variables you use) and 2) prevents "undefined variable" warnings the first time you go through the loop and concatenate the variable $rows. They may not display in the browser, but will clog up your error logs fast, even though they're just warnings.

- Yes, the previous stores a scalar string in memory, it's just a lot less data to store. :-) This approach allows you to easily do the very important if/else (what if nothing is found?) Additionally as mentioned you don't have to jump through hoops in programming working with the arrays.

- as you can see this "tracks" the "name" in the current row with the variable $currName. If it's the same as the last row, it displays a non breaking space (because tables display weird in IE if empty,) otherwise it displays the name and should only do so once for each of the same value (be sure to add order by event_date desc, event_name asc in your select). Rinse and repeat for other recurrent values (phone, etc.)

- This
list($name,$event,$date)

is a little used shortcut to

while ($row = mysql_fetch_array($result)) {
$name = $row['name']; // or $row[0]
$event = $row['event']; // or $row[1]
$date = $row['event_date']; // or $row[2]


... and works very well because mysql_fetch_array() returns both an associative and an indexed array, and we're using the latter to leverage with list().

- The above is formatted using the pre tags (find them in the links below posting) and doesn't allow tabs. Use only spaces. Many people use the quote tags to do a similar thing.


Thread source:: http://www.webmasterworld.com/php/4469810.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com