我一直在尝试列出各州及其城市以及每个城市的地点数量。有点像下面这样。
Texas
Austin (5)
Dallas (8)
Houston (3)
除了获取城市的计数并像上面那样显示之外,一切都在进行。
$sql ="SELECT DISTINCT
city,
state,
stateAbv,
COUNT(CASE WHEN open = 'Y' THEN 1 END) AS cnt
FROM $tbl_name
WHERE open = 'Y'
GROUP BY
city,
state,
stateAbv
ORDER BY
state;";
$result = mysqli_query($conn,$sql);
$num_columns = 1;
$rows = array();
$k=0;
while($row = mysqli_fetch_assoc($result)){
$state = $row['state'];
$stateAbv = $row['stateAbv'];
$city = $row['city'];
//Count of stores in every city
$values = mysqli_fetch_assoc($result);
$numStores = $values['cnt'];
if(!isset($rows[$row['state']])){
$rows[$row['state']] = array();
}
$rows[$row['state']][] = $city;
}
foreach($rows as $state => $cities){
echo '<b>'. $state .'</b>';
$cityChunks = array_chunk ($cities, $num_columns);
sort($cityChunks);
foreach($cityChunks as $row){
for($i=0; $i<$num_columns; $i++){
$city = isset($row[$i]) ? $row[$i] : "";
if ($k<3){
echo "$city($numStores)";
}
$k++;
}
}
$k=0;
}
通过将城市放入其中,我的 $rows
数组现在看起来像这样,但我在获取城市、计数并正确显示它时遇到了困难。
Array
(
[Alabama] => Array
(
[0] => Mobile
[1] => Auburn
[2] => Hoover
[3] => Foley
)
)
最佳答案
您的 $numStores
未向下传递到 $rows
数组。完成后,您可以使用 array_column() 获取每个州的所有位置,然后使用 array_sum() 获取总和。
while($row = mysqli_fetch_assoc($result)){
$state = $row['state'];
$stateAbv = $row['stateAbv'];
$city = $row['city'];
$numStores = $values['cnt'];
if (!isset($rows[$row['state']])){
$rows[$row['state']] = array();
}
$rows[$row['state']][] = ['city' => $city, 'numStores' => $numStores];
}
foreach($rows as $state => $cities){
echo $state." (".array_sum(array_column($cities, 'numStores')).")\n";
}
关于php - 将 MySQL 计数添加到 PHP 数组值中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207177/