我有一个已定义的数组。如果是列中的一个(例如Bayern'by')为空,那么我没有收到变量 $ row_wohn_by ,并且在结果之后得到的是:注意:未定义的变量:row_wohn_by < / p>
简单擦除不是另一种操作的解决方案。预期定义为 $ row_wohn_by , 0 (零)数字。
这是代码:
$states = array(
'Baden-Württemberg' => 'bw',
'Bayern' => 'by',
'Berlin' => 'be',
'Thüringen' => 'th'
);
$numb_rows = mysqli_query($conn, 'SELECT COUNT(*)
FROM members
WHERE priv_staat = "Deutschland"
');
$numb_row = mysqli_fetch_array($numb_rows);
$total_wohn = $numb_row[0];
$query_wohn = mysqli_query($conn, "SELECT `priv_land`, COUNT(*) AS `count` FROM `members` WHERE `priv_land` !=0 GROUP BY `priv_land`");
while ($item_wohn = $query_wohn->fetch_assoc()) {
${'row_wohn_'.$states[$item_wohn['priv_land']]} = $item_wohn['count'];
${'row_wohn_per_'.$states[$item_wohn['priv_land']]} = number_format((($item_wohn['count'] / $total_wohn)*100), 2, ',', ' '); // calulate in %
}
$row_wohn_all = $total_wohn-($row_wohn_bw + $row_wohn_by + $row_wohn_be + $row_wohn_th);
$row_wohn_per_all = number_format((($row_wohn_all / $total_wohn)*100), 2, ',', ' '); // calulate in %
感谢您的帮助。
答案 0 :(得分:1)
您写道:
预期定义 $ row_wohn_by 0
查看您的查询(SELECT priv_land, COUNT(*) AS count FROM members
),只有当没有行与priv_land = 'by'
时才会出现这种情况。因此,在查询之后的while
循环中,该变量永远不会被设置。
解决方案:使用值0初始化所有变量,并使用查询结果覆盖那些变量:
foreach($states as $privLand) {
${'row_wohn_' . $privLand} = 0;
${'row_wohn_per_' . $privLand} = 0;
}
$query_wohn = mysqli_query($conn, "SELECT `priv_land`, COUNT(*) AS `count` FROM `members` WHERE `priv_land` !=0 GROUP BY `priv_land`");
while ($item_wohn = $query_wohn->fetch_assoc()) {
${'row_wohn_'.$states[$item_wohn['priv_land']]} = $item_wohn['count'];
${'row_wohn_per_'.$states[$item_wohn['priv_land']]} = number_format((($item_wohn['count'] / $total_wohn)*100), 2, ',', ' '); // calulate in %
}
对于奖励积分,将所有内容重写为数组 - 通知会使生活变得更轻松(仅适用于$row_wohn_*
):
// Initialize all keys with value 0
$row_wohn = array_fill_keys($states, 0);
$query_wohn = mysqli_query($conn, "SELECT `priv_land`, COUNT(*) AS `count` FROM `members` WHERE `priv_land` !=0 GROUP BY `priv_land`");
while ($item_wohn = $query_wohn->fetch_assoc()) {
$row_wohn[ $states[$item_wohn['priv_land']] ] = $item_wohn['count'];
}
$row_wohn_all = $total_wohn - array_sum( $row_whon );