选择计数组并使用键和值输出到数组

时间:2018-08-26 12:55:02

标签: php arrays

我希望从数据库中选择number_id = 1的所有行,并将经验 ID分组在一起,并将每个计数的值输出到具有经验{{1} }作为键,id作为值。

count

所以结果应该是:

+------------+------------+
| number_id  | experience |
+------------+------------+
|  1         |  4         |
|  1         |  4         |
|  1         |  1         |
|  1         |  2         |
|  1         |  3         |
|  1         |  1         |
|  1         |  5         |
+------------+------------+

这是我到目前为止所拥有的:

4 => 2
1 => 2
2 => 1
3 => 1
5 => 1

输出此

$query = "SELECT COUNT(*) AS SUM FROM comments WHERE number_id = '1' GROUP BY experience";

$result = mysqli_query($conn, $query);
$experience = array();
if ($result->num_rows>0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $experience[] = $row['SUM'];
    }
}

print_r($experience);

但是我需要能够将它们的数组键更改为体验ID

我该怎么做?

1 个答案:

答案 0 :(得分:2)

只需选择experience并将其用作键。

$query = "SELECT experience, COUNT(*) AS SUM FROM comments WHERE number_id = '1' GROUP BY experience";

$result = mysqli_query($conn, $query);
$experience = array();
if ($result->num_rows>0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $experience[$row['experience']] = $row['SUM'];
    }
}

print_r($experience);