1

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?

2 Answers 2

2

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']);
Sign up to request clarification or add additional context in comments.

2 Comments

I did that, but i get double values inside the arrays. One with an associative key, and one with a Numeric Key, for each field.
Check my update. I'm now forcingPDO::FETCH_ASSOC in PDO::fectch(). This should fit your needs
0

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>";
}

1 Comment

I can't do that, because the script i'm doing already has a foreach. Inside this foreach, i have one variable, that's the user id, and it swap between two values. That's why i need to have the array as i said, so i can get different data based on the user_id.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.