【问题标题】:PHP - return SQL GROUP BY as array?PHP - 将 SQL GROUP BY 作为数组返回?
【发布时间】:2013-12-12 16:38:08
【问题描述】:

我正在尝试使用 GROUP BY 作为数组返回 MySQL 查询。

我的桌子是这样的:

user_id | type
--------------------
1       | test
1       | test
2       | test
1       | hello
1       | helloworld

还有我的代码和查询:

$number_of_workouts = array();
$query = mysqli_query(connect(),"SELECT type, COUNT(*) FROM `log` WHERE `user_id` = $user_id GROUP BY type");
$number_of_workouts = mysqli_fetch_assoc($query);

return $number_of_workouts;

上面的这段代码没有返回一个包含所有类型的数组,它只会返回一种类型的编号(假设$user_id = 1

如何将查询结果作为数组返回?

【问题讨论】:

  • 很难说出你在问什么。您的查询返回不止一行..但您只获取第一行。您想遍历结果并获取每一行吗?或者您想更改查询以使其仅返回一行?您的行有两列,但您将其提取到一个变量中,看起来它只是其中一列的值?清除输入,清除输出。处理第二个。

标签: php mysql arrays mysqli group-by


【解决方案1】:
mysqli_fetch_assoc($query);

仅从结果集中获取 1 行

如果你想要结果集中的所有行,你必须循环每一行并将其添加到堆栈中,如:

$number_of_workouts = array();
$query = mysqli_query(connect(),
    "SELECT type, COUNT(*) AS count
     FROM `log`
     WHERE `user_id` = $user_id
     GROUP BY type"
);

$array = array();

while ($number_of_workouts = mysqli_fetch_assoc($query)) {
    $array[$number_of_workouts['type']] = $number_of_workouts['count'];
}

// Now you have all results like you want in the variable array:
print_r($array);

// print count of type test:
echo $array['test'];

或者你试试mysqli_fetch_all() (http://www.php.net/manual/en/mysqli-result.fetch-all.php)

(抱歉更新太多)

【讨论】:

  • 那么如果我想回显test类型的编号呢?从阵列? print_r($array[0]); 会这样做,但是,“测试”不是 100% 是表中的第一种类型..:类似于 print_r($array['test']);?
【解决方案2】:

您在这里只获取第一条记录。将获取语句保持在while循环中

        while($number_of_workouts = mysqli_fetch_assoc($query))
        {
            echo "<pre>";
            print_r($number_of_workouts);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多