how to make array or arrays that is result from db to be indexed by ID from the table without looping?
example:
Array
(
[0] => Array
(
['user_id'] => 4567
['us开发者_高级运维er_name'] => 'John Doe'
['city'] => 'NY'
// and so on
)
[1] => Array
(
['user_id'] => 3732
['user_name'] => 'Janet Smith'
['city'] => 'LA'
// and so on
)
// and here many more rows
but I need this:
Array
(
[4567] => Array
(
['user_id'] => 4567
['user_name'] => 'John Doe'
['city'] => 'NY'
// and so on
)
[3732] => Array
(
['user_id'] => 3732
['user_name'] => 'Janet Smith'
['city'] => 'LA'
// and so on
)
// and here many more rows
So I can acces given row by it's id. The only one way I know is to loop this whole array that can be huge:
foreach($array_from_db as $row) {
$idexed_array_from_db[$row['user_id']] = $row;
}
Are there other ways to achieve this result ?
I don't think PDO can do this directly. There are other wrappers which can, such as ADODb with GetAssoc
$array=$db->GetAssoc("select user_id,user_name,city from user");
However, any wrapper is simply retrieving the result and building the array just as you describe in your question. The only difference is that your suggestion fetches the entire resultset into an array first, then generates your associative array from that.
If you're using PDO, your then a more memory efficient approach would be to read the results row-by-row and build the array that way.
精彩评论