user774528
user774528

Reputation: 187

PHP get MySQL database as associative array by row

I have a simple mySQL database table that I am loading into a PHP array. I would like the id column of the mySQL table (which is auto incremented, but I don't think that's relevant) to be the array key for each element of the PHP array, instead of the array being numeric.

Instead of this:

Array(
  Array(id=>'1', field1=>someval, field2=>val),
  Array(id=>'2', field1=>val, field2=>otherval),
  Array(id=>'4', field1=>val, field2=>otherval)
)

I want this:

Array(
  1=>Array(field1=>someval, field2=>val),
  2=>Array(field1=>val, field2=>otherval),
  4=>Array(field1=>val, field2=>otherval)
)

I don't care if id is left in the associative array for each row.

Is there a way to do this without looping through the original mySQL array and using up lots of processing time?

Upvotes: 0

Views: 2843

Answers (3)

Caleb Gray
Caleb Gray

Reputation: 3107

If you have PDO, you should definitely see Example #3 from the PDO documentation for fetchall: http://www.php.net/manual/en/pdostatement.fetchall.php#example-1022

Not only is this way more efficient use of your server's memory and processing power... it would also enable you to take advantage of several of PDO's other powerful APIs.

Upvotes: 0

xdazz
xdazz

Reputation: 160953

You can do it at the fetch time like this:

$query_ret = mysql_query(...);
$result = array();
while ($row = mysql_fetch_assoc($query_ret)) {
    $result[array_shift($row)] = $row;
}

Upvotes: 2

Hammerite
Hammerite

Reputation: 22350

"Is there a way to do this without looping through the original mySQL array and using up lots of processing time?"

I believe the answer to this is no. The best you can do is to try to be as efficient as possible when looping through the array.

Upvotes: 1

Related Questions