将MySQL计数添加到PHP数组值

时间:2019-05-19 11:07:49

标签: php mysql arrays multidimensional-array

我一直在尝试列出各州的州及其城市以及每个城市的地点数量。像下面这样。

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
    )
  )

1 个答案:

答案 0 :(得分:2)

您的$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";
}