Iterating Over DB Results (Idiom?)

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm using MDB2 to pull data from a MySQL database... works fine, e.g.:

$result = getData(...);

Now that I have the $result (a multidimensional array), what is the
PHP idiom for iterating through the set, e.g., to create an HTML table
of the data? Should I be thinking foreach() or something else?


Re: Iterating Over DB Results (Idiom?)

john said:
Quoted text here. Click to load it
Foreach would be the way to go. It doesn't care how many results there are
unlike other looping mechanisms which makes it the superior choice imho.

Typically though when looping over results from a database
while($row = fetchRowFromDB())
    // Process Row


is the way it would be done.

But given you already have all rows retrieved foreach is preferable.

Fermat was right.

Re: Iterating Over DB Results (Idiom?)

At Wed, 09 May 2007 07:51:16 -0700, john let his monkeys type:

Quoted text here. Click to load it

An example of how to traverse through a multidimensional array using
foreach (recursively):

function foreach_multi_arr (&$arr) {
    foreach ($arr as $key=>$value) {
         echo "[$key]=>";
        if (is_array($value)) {
        else {
            echo " $value<br />";  
// instead you could have a function acting on key/value pairs etc.

The '&' isn't required but if your array is huge the cost of copying each
subarray could become high. Similarly you may prepend $value
in the foreach with & to save on memory. (Only in PHP5)


Site Timeline