5

How can I create an array like the following in PHP from a database result set using a loop:

Array
(
    [T] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Timer
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => Tub
                )

        )

    [P] => Array
        (
            [0] => Array
                (
                    [id] => 3
                    [name] => Paper
                )

            [1] => Array
                (
                    [id] => 4
                    [name] => Puppy
                )

        )

)

You will notice that the array keys are a letter, which is taken from the 'name' value in the result set. The loop will be something like this:

while($result = $db->fetch($query) {

  $key = $result['name']{0};

  //  your answer  :-)

}
Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
Billy
  • 788
  • 1
  • 8
  • 17

3 Answers3

7

I think something like this should do it:

$sql = 'SELECT id, name FROM table';
$result = mysql_query( $sql);
$answer = array();
while( $row = mysql_fetch_assoc( $result))
{
    $answer[ strtoupper($row['name'][0]) ][] = $row;
}
mysql_free_result( $result);
var_dump( $answer);

OR, to be more specific (if your query is returning more columns than just id and name):

while( $row = mysql_fetch_assoc( $result))
{
    $answer[ strtoupper($row['name'][0]) ][] = array(
        'id' => $row['id'],
        'name' => $row['name']
    );
}
nickb
  • 59,313
  • 13
  • 108
  • 143
  • Ahh great, thanks! The part that makes this happen is the extra [] >> $array[$key][] = $result; rather than $array[$key] = $result;. Without that, the previous gets overwritten as we loop. – Billy Dec 08 '11 at 20:57
0
$indexArray = array(); // Array from Example
while($result = $db->fetch($query) {
    $key = $result['name']{0};
    if(!isset($indexArray[$key])) {
        $indexArray[$key] = array();
    }
    array_push($indexArray[$key], $result);
}
PseudoNinja
  • 2,846
  • 1
  • 27
  • 37
0
$results = array();
while($result = $db->fetch($query)) {
  $key = strtoupper($result['name'][0]);
  if(!isset($results[$key]))
    $results[$key] = array();
  $results[$key][] = $result;
}
connec
  • 7,231
  • 3
  • 23
  • 26