简单的PHP数组问题与键比较

Har*_*ody 1 php arrays compare key

整个下午我一直把头发拉出来.基本上,我有一个很长的值表(存储在SQL中),我想要遍历整个表并计算每个值显示的次数.我把值称为"pid"整数.

我想到的最好的方法是创建一个数组,其中PID作为数组的键,以及每个PID在表中出现的次数作为该键的值.然后浏览整个列表,并将PID添加到数组(如果它尚不存在),或者如果已经存在则递增单击值.目标是确定哪个PID具有最高的点击次数.

这听起来很简单,而且确实如此!我想我的语法必须在某处出错,因为一切似乎都是正确的.这是我第一次使用PHP中的数组,所以很好:)

非常感谢!

$tabulation = array();

while ($row = mysql_fetch_array($result)) {
    $pid = $row[1];  

    //if this post isn't in the tabulation array, add it w a click value of 1
    if ( !isset( $tabulation[$pid] ) ){ array_push( $tabulation[$pid], 1 ); }
    //if this post is already in the tabulation array, incrment its click value by 1
    else { 
        $t = $tabulation[$pid]; $t++; $tabulation[$pid] = $t;
    }
}

$highestClicksValue = -1;
$highestClicksPID = -1;
foreach ($tabulation as $pid => $clicks){
    if ($clicks > $highestClicksValue){ $highestClicksPID = $pid; }
    printf("PID: ". $tabulation[$pid] . " clicks: " . $tabulation[$clicks] . "<br />");
}
Run Code Online (Sandbox Code Playgroud)

Ken*_*wns 5

我知道你正在寻找一个PHP答案,但你认为这是SQL最擅长的吗?

select pid,count(*)
  from theTable
 group by pid
 order by count(*) desc
Run Code Online (Sandbox Code Playgroud)

只是一个想法...