Skip to content

Instantly share code, notes, and snippets.

@betweenbrain
Created February 26, 2014 21:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betweenbrain/9239337 to your computer and use it in GitHub Desktop.
Save betweenbrain/9239337 to your computer and use it in GitHub Desktop.
PHP PDO Fetch Array of Objects Indexed on Column Value
<?php
$sql = "SELECT id, name FROM `users`";
try
{
$query = $pdo->prepare($sql);
$query->execute();
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// Returns an array of standard class objects indexed on `id`
$results = $query->fetchAll(PDO::FETCH_OBJ|PDO::FETCH_GROUP);
// Strip the useless numbered array out of each object
$results = array_map('reset', $results);
/*
[42] => stdClass Object
(
[name] => Bob Jones
)
[10] => stdClass Object
(
[name] => Sam Bodee
)
[18] => stdClass Object
(
[name] => Alex Xela
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment