从数组循环 - PHP

Cycle from array - PHP

我有一个来自 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');
}       

首先用 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; ?>

但是你的结构有错误:

AZ 有 12 个用户
LT 有 12 个用户

LT 覆盖数组键中的 AZ。最好使用这种结构:

$languages = [
    [
        'country' => 'AZ',
        'number' => 12,
    ],
    [
        'country' => 'LT',
        'number' => 12,
    ],
];
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';
}

首先,为行命名。

$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>';
}