Search code examples
phparrayscycle

Cycle from array - PHP


i have an array from SQL which contains language and number how many users use this language.

Array looks like:

"$languages" => array (5)
12 => "CZ" (2)
4 => "SK" (2)
3 => "DE" (2)
2 => "RO" (2)
6 => NULL

As you can see this array is revert. I want to make statistic of them but it's kind a problem for me because only way i can get to this value is to write a count number of it (which is going to change ofc )

$langauges[12] -  answer CZ
$languages[CZ] -  answer error

Is there a way how i can make cycle from this array to let's say echo it to some HTML?

What i want is :

<div>
<div class="country"> CZ </div>
<div class="number"> 12 </div>
</div>

SQL looks like:

function getLanguageStatistic()
{
    return $this->db->fetchPairs('SELECT COUNT(*), language FROM users GROUP BY language ORDER BY COUNT(language) DESC');
}       

Solution

  • First, name the row.

    $request = $this->db->query("SELECT COUNT(*) as nbr
                                      , language FROM users 
                                 GROUP BY language 
                                 ORDER BY COUNT(language) DESC");
    

    Then (using PDO, but same for others) :

    $datas = $request->fetchAll();
    
    foreach($datas as $elem){
      echo '<div>
                <div class="country">'.$elem["language"].'</div>
                <div class="number">'.$elem["nbr"].'</div>
            </div>';
    }