2

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!

2
  • you should post some code instead of writing "When fetching an array..." Commented Apr 8, 2011 at 22:05
  • Then he'll post code about using mysql_* :((((( Commented Apr 8, 2011 at 22:07

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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', ...)))
0

Depending on which library you are using:

mysql_fetch_assoc()

mysqli_fetch_assoc()

PDO fetches both by default.

3 Comments

He wants the first column to the the array key of the result set.
@Kevin Peno Oh, that wasn't entirely obvious from the original version of this question. Sorry.
@ Kevin Peno No offense taken, either. Thanks. :)

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.