我正在尝试从下表输出数据,如下所示:
Level 1 - [Count Figure]
Level 2 - [Count Figure]
Level 3 - [Count Figure]
Level 4 - [Count Figure]
Level 10 - [Count Figure]
标题(1 级等)必须保留在那里,并且当前是硬编码的。我知道有多少个不同的级别,所以就是这样。我的问题是,如何检测它是哪个级别并输出它的计数。我需要那里的所有级别,无论是否有计数。如果数据库中没有计数数字,则计数将读取 0。
我现在的做法是使用案例。我尝试用if()
这样做,但失败了。使用大小写的问题是,如果特定标题类型没有计数,if不会输出标题名称,所以我可以将计数打印为0
你能帮忙吗?
编辑我不需要使用switch
.其他任何事情都可以。
我的代码
function staticCountArticles($country){
global $conn;
$countArticles = $conn->prepare('select count(id) as artcCount, artc_type from contributions where artc_status = 2 and artc_country = :country group by artc_type');
$countArticles->bindParam(':country',$country);
$countArticles->execute();
$countArticles->bindColumn('artcCount',$artcCount);
$countArticles->bindColumn('artc_type',$artcType);
$hasArticles = $countArticles->rowCount();
while( $artcData = $countArticles->fetch()) {
switch($artcType){
case 1:
echo '<b>Level 1</b><br>';
if($artcCount > 0){ echo $artcCount.'<br>';} else { echo 'Nothing here yet <br>';}
break;
case 2:
echo '<b>Level 2</b><br>';
if($artcCount > 0){ echo $artcCount.'<br>';} else { echo 'Nothing here yet <br>';}
break;
case 3:
echo '<b>Level 3</b><br>';
if($artcCount > 0){ echo $artcCount.'<br>';} else { echo 'Nothing here yet <br>';}
break;
case 4:
echo '<b>Level 4</b><br>';
if($artcCount > 0){ echo $artcCount.'<br>';} else { echo 'Nothing here yet <br>';}
break;
case 10:
echo '<b>Level 10</b><br>';
if($artcCount > 0){ echo $artcCount.'<br>';} else { echo 'Nothing here yet <br>';}
break;
default:
echo 'Unidentified type encountered<br>';
}
}
}
数据
"id" "artc_type" "artc_status" "artc_user" "artc_country"
"1" "1" "2" "1" "US"
"2" "1" "2" "1" "US"
"3" "1" "2" "1" "US"
"4" "2" "2" "2" "US"
"5" "2" "2" "2" "US"
"6" "2" "2" "2" "US"
"7" "4" "2" "2" "US"
"8" "4" "2" "3" "US"
"9" "4" "2" "3" "US"
"10" "10" "2" "3" "US"
"11" "10" "2" "4" "US"
"12" "10" "2" "4" "US"
"13" "10" "2" "4" "US"
"14" "10" "2" "4" "US"
请尝试此方法。我们不是尝试打印结果,而是将所有计数初始化为 0 并将它们存储在输出数组中。对于输出,我们遍历打印数据的数组。这允许您打印 0 值,因为它们不会因处理数据库数据而更改
function staticCountArticles($country){
global $conn;
$countArticles = $conn->prepare('select count(id) as artcCount, artc_type from contributions where artc_status = 2 and artc_country = :country group by artc_type');
$countArticles->bindParam(':country',$country);
$countArticles->execute();
$countArticles->bindColumn('artcCount',$artcCount);
$countArticles->bindColumn('artc_type',$artcType);
$hasArticles = $countArticles->rowCount();
// Init our output array
$output = Array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 10 => 0);
while( $artcData = $countArticles->fetch()) {
if($artcCount > 0) $output[$artcType] = $artcCount;
}
// Print the results
foreach($output as $level => $item)
{
echo '<b>Level '.$level.'</b><br>';
if($item > 0){ echo $item.'<br>';} else { echo 'Nothing here yet <br>';}
}
}