【问题标题】:Add MySQL count into PHP array values将 MySQL 计数添加到 PHP 数组值中
【发布时间】:2019-05-19 11:07:49
【问题描述】:

我一直在尝试列出州组及其城市和每个城市的位置数量。有点像下面。

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

【问题讨论】:

    标签: php mysql arrays multidimensional-array


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      • 2016-03-28
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      相关资源
      最近更新 更多