php - 需要foreach循环才能显示一组值

时间:2013-02-27 23:02:49

标签: php

我正在尝试编写一个从SQL查询中获取结果的脚本,并且当它通过每个结果时它检查以查看$ row [13]的名称应该是什么,然后我想要通过每个查询结果它识别任何相似的名称并保持它看到该名称的次数。我以为我有一个循环计算出来会计算同一个名字在数组中出现的次数然后显示它。我正在寻找的最终结果是

Operations - 87
Training - 32
HR - 12

但是在我运行此代码之后:

      while($row = mysql_fetch_array($result_id))
  {
        $profile8 = mysql_query
                    ("
                        SELECT org
                        FROM cost_centers
                        WHERE cost_center = '$row[13]'
                    ")
                    or die(mysql_error());
                    $anymatches=mysql_num_rows($profile8);
                        while($pro8 = mysql_fetch_array($profile8))
                        {
                            $orgnames = $pro8[0];
                        }


                            $names[] = $orgnames;

                            $newArray = array_count_values($names);

                            foreach ($newArray as $key => $value) {
                                echo "$key - $value <br />";
                            }

  }

我最终计算得如此:

HR - 1 
HR - 1 
Communications - 1 
HR - 1 
Communications - 1 
- 1 
HR - 1 
Communications - 1 
- 2 
HR - 1 
Communications - 1 
- 3 
HR - 1 
Communications - 1 
- 4 
HR - 2 
Communications - 1 
- 4 
HR - 3 
Communications - 1 
- 4 
HR - 3 
Communications - 1 
- 4 
Operations - 1 
HR - 4 
Communications - 1 
- 4 
Operations - 1 
HR - 4 
Communications - 1 
- 5 
Operations - 1 
HR - 4 
Communications - 1 
- 6 
Operations - 1 
HR - 4 
Communications - 1 
- 6 
Operations - 2 
HR - 4 
Communications - 1 
- 6 
Operations - 3 
HR - 4 

所以它几乎看起来像它的分组然后计数,然后重新组合,因为它不断添加其计数。我希望这是有意义的,并提前感谢。

4 个答案:

答案 0 :(得分:1)

为什么不使用以下查询:

SELECT 
    SUM(IF(org='HR', 1, 0)) AS HRCount,
    SUM(IF(org='Communications', 1, 0)) AS ComCount,
    SUM(IF(org='Operations', 1, 0)) AS OpCount,
FROM cost_centers
WHERE cost_center = '$row[13]'

然后您可以通过调用$row["HRCount"];

来访问这些值

答案 1 :(得分:1)

这很开心,因为你每次都在循环内打印计数器。它必须如何:

<?php

while($row = mysql_fetch_array($result_id))
{
    $profile8 = mysql_query("
        SELECT org
        FROM cost_centers
        WHERE cost_center = '$row[13]'")
    or die(mysql_error());

    $anymatches=mysql_num_rows($profile8);
    while($pro8 = mysql_fetch_array($profile8))
    {
        $orgnames = $pro8[0];
        $names[] = $orgnames;
    }
}

$newArray = array_count_values($names);

foreach ($newArray as $key => $value) {
    echo "$key - $value <br />";
}

无论如何,对第一行中的每一行进行新查询都不是一个好的选择。您应该更好地学习SQL,特别是关于JOIN和(在您的情况下)COUNT运算符。

答案 2 :(得分:0)

试试这个:

SELECT cost_centers.org, count(*) FROM cost_centers WHERE cost_center = what_you_want GROUP BY cost_centers.org

答案 3 :(得分:0)

你走在正确的轨道上。

在制作阵列之前:

$org = array();

现在,在foreach中,使用$ key在新数组中创建一个键,然后添加一个

foreach ($newArray as $key => $value) {
    $org[$key] += 1;
}

当你完成while($ row = mysql_fetch_array($ result_id))循环时,再做一个foreach循环并显示结果。

foreach($org as $name => $count){
    echo $name . " = " . $count . "<br />";
}