PHP如何在foreach循环中计算相同的单词

时间:2015-01-12 09:51:16

标签: php arrays loops foreach count

我在foreach循环中有这个结果:

Tonsilitis
Tonsilitis
Laryngitis
Rhinosinusitis Akut
Rhinosinusitis Akut
Rhinosinusitis Akut
Common Cold
Common Cold
Common Cold
Rhinitis Alergi

这是我的剧本:

foreach ($results as $data) :
   $final = $data->nama_diagnosis . '<br>';
   echo $final;
endforeach;

我的问题是,如何在循环中或循环外计算相同的单词。我能这样做吗?请给我解决方案。因此,我想像这样计算它们:

Tonsilitis = 2
Laryngitis = 1
Rhinosinusitis Akut = 3
Common Cold = 3
Rhinitis Alergi = 1

或许我可以过滤同一个词,所以我只得到最多的词,如鼻窦炎和普通感冒。请帮我。 感谢

4 个答案:

答案 0 :(得分:4)

您可以尝试这样的方法,使用foreach循环遍历数组并使用带isset的三元运算符来安全地分配和递增每个匹配项:

$count = array();
foreach ($results as $result)
    isset($count[$data]) ? $count[$data]++ : $count[$data] = 1;

Example

答案 1 :(得分:2)

在foreach循环中将单词及其计数保存到数组中,然后再创建一个循环并写入金额。

<?php

$results = array(
    array('nama_diagnosis' => 'Tonsilitis'),
    array('nama_diagnosis' => 'Tonsilitis'),
    array('nama_diagnosis' => 'Laryngitis'),
    array('nama_diagnosis' => 'Rhinosinusitis Akut'),
    array('nama_diagnosis' => 'Rhinosinusitis Akut'),
    array('nama_diagnosis' => 'Rhinosinusitis Akut'),
    array('nama_diagnosis' => 'Common Cold'),
    array('nama_diagnosis' => 'Common Cold'),
    array('nama_diagnosis' => 'Common Cold'),
    array('nama_diagnosis' => 'Rhinitis Alergi')
);

$res = array();
foreach ($results as $words) {  // changed $word to $words
    foreach ($words as $word) { // this foreach added
        if (isset($res[$word])) {
            $res[$word] += 1;
        } else {
            $res[$word] = 1;
        }
    } // end of nested foreach which was added
}

foreach ($res as $word => $count) {
    echo $word . ' (' . $count . ')<br>';
}

/*
    output:

    Tonsilitis (2)
    Laryngitis (1)
    Rhinosinusitis Akut (3)
    Common Cold (3)
    Rhinitis Alergi (1)
*/

?>

答案 2 :(得分:1)

尝试 -

$counts = array();
foreach ($results as $data) :
   $final = $data->nama_diagnosis . '<br>';
   if (array_key_exists($data->nama_diagnosis, $counts)) {
        $counts[$data->nama_diagnosis] += 1;
   } else {
        $count[$data->nama_diagnosis] = 1;
   }
endforeach;

foreach ($counts as $key => $val) { 
    echo $key.' = '.$val;
}

答案 3 :(得分:0)

这应该适合你:

<?php

    $results = array("Tonsilitis", "Tonsilitis", "Laryngitis", "Rhinosinusitis Akut", "Rhinosinusitis Akut", "Rhinosinusitis Akut", "Common Cold", "Common Cold", "Common Cold", "Rhinitis Alergi");
    $counter = array();


    foreach ($results as $data):
        if(in_array($data->nama_diagnosis, array_flip($counter)))
            $counter[$data->nama_diagnosis]++;
        else
            $counter[$data->nama_diagnosis] = 1;
    endforeach;

    foreach ($counter as $key => $data)
       echo $key . " = " . $data . "<br />"; 

?>

输出:

Tonsilitis = 2
Laryngitis = 1
Rhinosinusitis Akut = 3
Common Cold = 3
Rhinitis Alergi = 1