2013-02-20 65 views
0

首先,感谢您的任何帮助。从关联数组中计算唯一值

我已经花了无数这里时间和其他论坛,试图找到我确切的解决方案,但无论是1)我不理解一个人的我读过或2)我还没有找到正确的答案。

在PHP中,我碰到一个比较复杂的查询返回类似于一组记录:

id | name | direction| 
1 aaa east 
2 bbb west 
3 ccc east 

我创建了一个关联数组,如:

$query=("select * from foo"); 
$result=mysql_query($query); 
$array=mysql_fetch_assoc($result); 

现在,我需要做的事似乎很简单,但由于某种原因,我并没有理解这个概念。 我需要循环遍历整个$数组,并返回我想要指定的任何值的计数,并将该计数存储在变量中。

即显示east在“方向”列中出现多少次,并将其放入名为$eastcount的变量中。

我已经试过各种组合使用foreach循环增量计数和使用array_count_values都试过,但都没有能够把拼在一起:/

+4

向我们展示你已经尝试 – 2013-02-20 01:41:18

+0

什么老实说,我一直试图两天这么列出一切会采取另一种5天:)我由于实际结果集取自子查询,因此无法轻松获得计数... – dan 2013-02-20 01:43:29

+1

'mysql_fetch_assoc'只提取一行 – 2013-02-20 01:43:38

回答

0
// build query 
$query=("select * from foo"); 

// execute query 
$result=mysql_query($query); 

// declare vars 
$east_count = 0; 

// iterate through results 
while ($data = mysql_fetch_array($result)) { 

    // grab DIRECTION column value 
    $direction = $data['direction']; 

    // detect 'east' 
    if ($direction == 'east') { 

     // increment 'east' count 
     $east_count++; 
    } 
} 

// print # of times we had 'east' 
echo("direction said 'east' $east_count times"); 
+0

这工作,比我想象的更简单。谢谢! – dan 2013-02-20 02:02:00

+0

很高兴为你效劳。希望你会把它作为回答:) – cre8value 2013-02-20 02:32:09

+0

我刚刚做了...再次感谢。 – dan 2013-02-20 02:55:32

0

首先,大家应该使用的mysqli代替。但是,无论如何,我希望这是有道理的。

if ($result) { 
    $count = 0; 
    while ($row = mysql_fetch_assoc($result)) { 
     if ($row["route"] === "east") { 
      $count += 1; 
     } 
    } 
    return $count; 
} 
1

如何:

query=("select * from foo"); 
$result=mysql_query($query); 

$directions = array(); 

while($direction = mysql_fetch_assoc($result) { 
    $directions[] = $direction['direction']; 
} 

$directionCounts = array_count_values($directions); 

//now you can access your counts like this: 
    echo $directionCounts['east']; 
+0

+1为好的解决方案 – 2013-02-20 03:54:38

+0

谢谢你,Prasanth – Ares 2013-02-20 04:19:41