2

Lets say I have a MySQL table, Users, like this -

-----------------------------------------
ID      | FirstName    | LastName
-----------------------------------------
1       | ABC          | XYZ
2       | DEF          | LMN
3       | GHI          | PQR
-----------------------------------------

And I can fetch results using simple MySQL query like

SELECT ID, FirstName, LastName FROM Users

Now what I am looking for is to store the query results in an associative array form. The structure would be something like this -

Array
(
[ID] => Array
(
[0] => FirstName
[1] => LastName
)
)

SO the above query result should get stored in an array like this -

Array
(
  [1] => Array
  (
  [0] => ABC
  [1] => XYZ
  )
  [2] => Array
  (
  [0] => DEF
  [1] => LMN
  )
  [3] => Array
  (
  [0] => GHI
  [1] => PQR
  )
)

I know about array_push. But I wonder if that needs to be used. How can get this result ?

1
  • what are you using? mysql api? mysqli extension? pdo?
    – mishu
    Mar 29, 2012 at 10:01

3 Answers 3

1
$result = mysql_query('SELECT ID, FirstName, LastName FROM Users');

$data = array();
while ($row = mysql_fetch_assoc($result)) {
  $id = array_shift($row); // Shifts first element
  $data[$id] = $row; 
}

You can use inside while a shorter version $data[array_shift($row)] = $row;

0
1

You have to put in your Database connection informations, maybe change the SQL-Statement a bit and the column-names inside the while-loop.

$db = @new mysqli('HOST', 'USER', 'PASS', 'DBNAME');
$res = $db->query("SELECT * FROM `Users`");

$yourdata = array();

if ($res && $db->errno == 0) {
   while ($row == $res->fetch_object()) {
      $yourdata[$row->ID] = array(0 => $row->firstname, 1 => $row->lastname);
   }
}
0

This is a bit more associative than you wanted :)

$temp = array();
$arr = array();

$r = mysql_query("<your query>");
while ($row = mysql_fetch_assoc($r))
{
   $temp['fname'] = $row['FirstName'];
   $temp['lname'] = $row['LastName'];
   $arr[$row['ID']] = $temp;
   unset($temp);
}

Should output

Array (
   [1] => Array (
       [fname]   => ABC
       [lname]   => XYZ
   )
)
.
.
.
etc

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.