简体   繁体   中英

PHP fetch MySQL array with an index

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!

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

Depending on which library you are using:

mysql_fetch_assoc()

mysqli_fetch_assoc()

PDO fetches both by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM