Reputation: 1576
I do have a query to get two users from a MySQL database. I'm using PDO.
This is the returned array, using fetchAll(PDO::FETCH_ASSOC)
array(2) {
[0]=>
array(8) {
["user_id"]=>
string(1) "4"
["last_activity"]=>
string(10) "1367361208"
["status"]=>
string(1) "1"
["username"]=>
string(4) "WiS3"
["gender"]=>
string(1) "1"
["a_last_update"]=>
string(10) "1365785841"
["user_level"]=>
string(1) "6"
["level_color"]=>
string(6) "FC0000"
}
[1]=>
array(8) {
["user_id"]=>
string(2) "19"
["last_activity"]=>
string(10) "1367359866"
["status"]=>
string(1) "2"
["username"]=>
string(5) "Admin"
["gender"]=>
string(1) "1"
["a_last_update"]=>
string(10) "1366690422"
["user_level"]=>
string(1) "7"
["level_color"]=>
string(6) "008AFF"
}
}
Since the rows Array are Numeric, to get data from, i have to do $row[0][field]
, $row[1][field]
But i want it to be Associative using user_id
, so i can do $row[user_id][field]
It is possible? How i can do that?
Upvotes: 1
Views: 1273
Reputation: 157947
Sorry, no built-in for that. You'll have to use PDOStatement::fetch()
and populate the array by yourself:
$result = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// note that $row['user_id'] will currently a string
// if you need integers as indexes then use intval($row['user_id']);
$result[$row['user_id']] = $row;
}
// dump all records
var_dump($result);
// dump username of user with uid = 4
var_dump($result['4']['username']);
Upvotes: 2
Reputation: 11393
It is already an associative array, containing several distinct records.
Use foreach
to get each record separately:
foreach($rows as $id => $row)
{
echo "Record n°" . $id . ": " . $row['user_id'] . "<br>";
}
Upvotes: 0