PDO associative arrays - return associative

bestprogrammerintheworld picture bestprogrammerintheworld · Mar 20, 2013 · Viewed 33.9k times · Source

I have this code:

$dbInstance = DB_Instance::getDBO();
$statement = $dbInstance->prepare("SELECT id, name FROM language ORDER BY id");
$statement->execute();      
$rows = $statement->fetchAll(); 

//Create associative array wuth id set as an index in array
$languages = array();
foreach($rows as $r) {
    $languages[$r['id']] = $r['name'];
}
return $languages;

I can't figure out how to use PDO-statement to achieve the same result that array $languages produces. I've tried some different fetch_styles.

I've tried some different styles and I could get like:

[0] svenska
[1] engelska

but I want like:

[1] svenska
[2] engelska

(where 1 and 2 are the values of id in database)

I guess I could create a function and call that with FETCH_FUNC but I'm not sure that would be so great either.

Is the above the best/cleanest way to do it?

Answer

Miron Yanovskiy picture Miron Yanovskiy · Feb 13, 2014

Everybody forgot about the

$sth->fetchAll(PDO::FETCH_KEY_PAIR);