0

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!

4 Answers 4

2
$result = mysql_query($q);
while ($row = mysql_fetch_assoc($result)) {
  $array[$row["id"]] = $row["name"];
}
Sign up to request clarification or add additional context in comments.

3 Comments

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".
Pretend it's called $foo then.
I'm naming $jordan for sure :) Thanks guys!
1

yes,

$names = array();
foreach ($rows as $r) {
   $names[$r['id']] = $r['name'];
}

Comments

0

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

$array = $db->GetAssoc("select id,name from mytable");

Comments

0

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');

Comments

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.