Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Much like this previous question, I wish to store a MySQL column in a php array (as opposed to storing by row). However, I want the array indexes to match those of the database's primary key.

For instance, for the following database:

id name
1 Joe
2 Mary
9 Tony

$name['9'] == "Tony"

Is such a thing possible?

Thanks!

share|improve this question
add comment

4 Answers

up vote 2 down vote accepted
$result = mysql_query($q);
while ($row = mysql_fetch_assoc($result)) {
  $array[$row["id"]] = $row["name"];
}
share|improve this answer
 
Note that you need to initialize the array before the while loop with $array = array(); or it will throw a notice on the first row. Also, please don't name your variable "$array". –  Jordan Jan 15 '10 at 22:33
1  
Pretend it's called $foo then. –  Randy Jan 15 '10 at 22:35
 
or maybe $jordan :) –  Paul Dixon Jan 15 '10 at 22:37
 
I'm naming $jordan for sure :) Thanks guys! –  David Chouinard Jan 15 '10 at 22:59
add comment

yes,

$names = array();
foreach ($rows as $r) {
   $names[$r['id']] = $r['name'];
}
share|improve this answer
add comment

A wrapper library can make this easier, e.g. with ADODb:

$array = $db->GetAssoc("select id,name from mytable");
share|improve this answer
add comment

Once I have my row results as arrays, I use this method:

function convertArrayToMap(&$list, $attribute, $use_reference=FALSE) {
    $result = array();
    for ($i=0; $i < count($list); $i++) {
        if ($use_reference) $result[$list[$i][$attribute]] = &$list[$i];
        else $result[$list[$i][$attribute]] = $list[$i];
    }
    return $result;
}

And the method call:

$mapOfData = convertArrayToMap($mysql_results, 'ID');
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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