不确定如何解释这一点,但是:
假设我有$ array并且我需要查询MySQL数据库以获取一行的值'name',然后将数组键存储为该名称,但随后将该值存储为多少有的行。
所以我们在数据库中有$ array ['bob'],值为100 bobs,然后在数据库中有另一个$ array ['john'],值为20 bobs。我怎么能快点做到这一点?
答案 0 :(得分:2)
使用单个查询和group by
子句:
$query = "select name, count(*) from my_table group by name";
从数据库中提取数据的具体细节我留给您,但假设您最终得到了多维行数组,您可以使用以下命令将名称映射到该名称的频率:
$frequency = array();
foreach ($rows as $row)
$frequency[$row[0]] = (int)$row[1];
答案 1 :(得分:2)
使用PDO,它看起来像这样:
$sth = $conn->prepare("SELECT name, count(*) FROM names GROUP BY name");
$sth->execute();
/* Group values by the first column */
$array = $conn->fetchAll(PDO::FETCH_COLUMN);
结果:
$array = array('bob'=>'100', 'john'=>'20');
答案 2 :(得分:2)
mysql> SELECT name, count(name) as count FROM names GROUP BY name;
+------+-------+
| name | count |
+------+-------+
| bill | 6 |
| bob | 11 |
| joe | 13 |
+------+-------+
可以这样做:
$array = Array('bob'=>0,'bill'=>0,'joe'=>0);
$sql = "SELECT name, count(name) as count
FROM names
WHERE name IN ('".implode("','",array_map('mysql_real_escape_string',array_keys($array)))."')
GROUP BY name";
if ($result = mysql_query($sql)){
while (($row = mysql_fetch_array($result)) !== false)
$array[$row['name']] = $row['count'];
}
var_dump($array);
呈现:
array(3) {
["bob"]=>
string(2) "11"
["bill"]=>
string(1) "6"
["joe"]=>
string(2) "13"
}