我有一个来自SQL的数组,其中包含有多少用户使用此语言的语言和编号。
数组如下所示:
"$languages" => array (5)
12 => "CZ" (2)
4 => "SK" (2)
3 => "DE" (2)
2 => "RO" (2)
6 => NULL
正如您所看到的,此数组已恢复。我想对它们进行统计,但这对我来说是一个问题,因为只有我能得到这个值的方法是写一个它的计数(这将改变ofc)
$langauges[12] - answer CZ
$languages[CZ] - answer error
有没有一种方法可以让我从这个数组中循环来让它回复一些HTML?
我想要的是:
<div>
<div class="country"> CZ </div>
<div class="number"> 12 </div>
</div>
SQL看起来像:
function getLanguageStatistic()
{
return $this->db->fetchPairs('SELECT COUNT(*), language FROM users GROUP BY language ORDER BY COUNT(language) DESC');
}
答案 0 :(得分:3)
首先,命名该行。
$request = $this->db->query("SELECT COUNT(*) as nbr
, language FROM users
GROUP BY language
ORDER BY COUNT(language) DESC");
然后(使用PDO,但对其他人也一样):
$datas = $request->fetchAll();
foreach($datas as $elem){
echo '<div>
<div class="country">'.$elem["language"].'</div>
<div class="number">'.$elem["nbr"].'</div>
</div>';
}
答案 1 :(得分:1)
首先使用asort()
做foreach
asort($languages);
foreach ($language as $frq => $acronym): ?>
<div>
<div class="country"> <?php echo $acronym; ?> </div>
<div class="number"> <?php echo $frq; ?> </div>
</div>
<?php endforeach; ?>
但是你的结构有bug:
AZ有12位用户
LT有12个用户
LT在数组键中覆盖AZ。更好地使用这种结构:
$languages = [
[
'country' => 'AZ',
'number' => 12,
],
[
'country' => 'LT',
'number' => 12,
],
];
答案 2 :(得分:-2)
Use a foreach loop to iterate through all the address, as seen below:
foreach($blockIP as $ip)
{
if($_SERVER['REMOTE_ADDR'] == $ip){
echo 'blocked';
}else{
echo 'not blocked';
}
}
If you only need to check to see if the current address is in the array, use the in_array() function:
if(in_array($_SERVER['REMOTE_ADDR'], $blockIP)){
echo 'blocked';
}else{
echo 'not blocked';
}