Create PHP array from MySQL column, using auto_increment column as index
Much like this previous question, I wish to store a开发者_Go百科 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!
$result = mysql_query($q);
while ($row = mysql_fetch_assoc($result)) {
$array[$row["id"]] = $row["name"];
}
yes,
$names = array();
foreach ($rows as $r) {
$names[$r['id']] = $r['name'];
}
A wrapper library can make this easier, e.g. with ADODb:
$array = $db->GetAssoc("select id,name from mytable");
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');
精彩评论