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  :-)

}

3 Answers 3

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']
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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);
}

Comments

0
$results = array();
while($result = $db->fetch($query)) {
  $key = strtoupper($result['name'][0]);
  if(!isset($results[$key]))
    $results[$key] = array();
  $results[$key][] = $result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.