我认为最好分一些地提出这些问题而不是一个大问题。这是之前已解决的问题的延续。我有以下查询提取每个国家/地区的国家/地区和计数。
$query = mysqli_query($con, "SELECT COUNT(id) AS countCnt, country FROM users GROUP BY country ORDER BY COUNT(id) DESC");
我试图在数组中获取这些内容,如下所示我可以将它们分配为变量:
$country_text = ['USA', 'Canada', 'England', 'Australia', 'New Zealand', etc...];
$country_count = [15, 10, 5, 3, 2, etc...];
一旦分配了这些,我想按如下方式显示它们:
for($i = 0; $i < 195; $i++) {
echo "['{$country_text[$i]}'" . "," . "{$country_count[$i]}],";
}
这三个代码链接在一起是完整的。我所面临的挑战是创建数组&amp;将它们指定为变量。任何帮助将不胜感激。
答案 0 :(得分:1)
您可以通过以下方式实现此目的:
//do a query and run
$query = mysqli_query($con, "SELECT COUNT(id) AS countCnt, country FROM users GROUP BY country ORDER BY COUNT(id) DESC");
$countries = [];
//iterate through values from query
while($row = mysqli_fetch_assoc($query)) {
$country = $row['country'];
$countryCount = $row['countCnt'];
//create and array with data, formatted as ['USA' => '15', 'Canada' => '10' , ...]
$countries[$country] = $countryCount;
}
//Create both arrays
$country_text = array_keys($countries);
$country_count = array_values($countries);
或者,而不是做
for($i = 0; $i < 195; $i++) {
echo "['{$country_text[$i]}'" . "," . "{$country_count[$i]}],";
}
你可以做到
foreach($countries as $country => $count) {
echo "[".$country." ," .$count."],";
}
答案 1 :(得分:0)
您需要的格式称为$query = mysqli_query($con, "SELECT COUNT(id) AS countCnt, country FROM users GROUP BY country ORDER BY COUNT(id) DESC");
$countries = [];
while($row = mysqli_fetch_assoc($query)) {
$countries[] = [$row['country'], $row['countCnt']];
}
echo json_encode($countries);
。 不要发明轮子,一切都已经发明了:
sparkR.session(sparkConfig = list(spark.cores.max='2',spark.executor.memory = '8g'))