我正在尝试输出下表中的数据:
Level 1 - [Count Figure]
Level 2 - [Count Figure]
Level 3 - [Count Figure]
Level 4 - [Count Figure]
Level 10 - [Count Figure]
标题(1级等)必须保留在那里,并且目前是硬编码的。我知道有多少不同的级别,所以就是这样。 我的问题是,我如何检测它是哪个级别并输出它的计数。我需要那里的所有级别,无论是否有计数。 如果数据库中没有计数数字,则count将读为0。
我现在这样做的方式就是大小写。我尝试用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 :(得分:1)
请尝试这种方法。我们不是尝试打印结果,而是将所有计数初始化为0并将它们存储在输出数组中。对于输出,我们循环遍历数组打印数据。这样您甚至可以打印0值,因为它们不会因DB数据的处理而被更改
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>';}
}
}