Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

When fetching an array from MySQL the rows are typically returned with a key from 0 to the size of your recordset:

row[0][key][value]

Is it possible to have one of the fields from the select statement returned as the key in the array?

For example. Assuming my data set has StudentID, Name, City, etc.

How can I select into an array where I could refer to the StudentID as the index like this:

rows[StudentID][Name]
rows[StudentID][City]
etc.

Thanks!

share|improve this question
    
you should post some code instead of writing "When fetching an array..." – Your Common Sense Apr 8 '11 at 22:05
    
Then he'll post code about using mysql_* :((((( – Kevin Peno Apr 8 '11 at 22:07

2 Answers 2

up vote 1 down vote accepted

PDOStatement::fetchAll

To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.

// Other PDO stuff to get a statement - abstract below
$result = PDOStatement::fetchAll( PDO::FETCH_COLUMN | PDO::FETCH_GROUP, 0 );

See example 3 on this page

share|improve this answer
    
This works, but not as needed, when e.g. column 0 is an (unique) ID like here StudentID. Then you'll always get an "extra" index 0 level, like e.g. StudentID=4: ARRAY(4=>ARRAY(0=>ARRAY('StudendID'=>4, 'StudendName'=>'Joe', ...))) – djot Sep 19 '13 at 22:28

Depending on which library you are using:

mysql_fetch_assoc()

mysqli_fetch_assoc()

PDO fetches both by default.

share|improve this answer
    
He wants the first column to the the array key of the result set. – Kevin Peno Apr 8 '11 at 22:06
    
@Kevin Peno Oh, that wasn't entirely obvious from the original version of this question. Sorry. – Tieson T. Apr 8 '11 at 22:11
    
np, just pointing it out :) – Kevin Peno Apr 8 '11 at 22:12
    
@ Kevin Peno No offense taken, either. Thanks. :) – Tieson T. Apr 8 '11 at 22:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.