Iterating Over DB Results (Idiom?)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • john

    #1

    Iterating Over DB Results (Idiom?)

    All:

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

    $result = getData(...);

    Now that I have the $result (a multidimensiona l 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?

    Thanks,
    jpuopolo

  • Schraalhans Keukenmeester

    #2
    Re: Iterating Over DB Results (Idiom?)

    At Wed, 09 May 2007 07:51:16 -0700, john let his monkeys type:
    All:
    >
    I'm using MDB2 to pull data from a MySQL database... works fine, e.g.:
    >
    $result = getData(...);
    >
    Now that I have the $result (a multidimensiona l 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?
    >
    Thanks,
    jpuopolo
    An example of how to traverse through a multidimensiona l array using
    foreach (recursively):

    function foreach_multi_a rr (&$arr) {
    foreach ($arr as $key=>$value) {
    echo "[$key]=>";
    if (is_array($valu e)) {
    foreach_multi_a rr($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)

    HTH
    Sh.

    Comment

    Working...