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

时间:2011-02-21 01:28:15

标签: php arrays key compare

整个下午,我一直把头发拉出来。基本上,我有一个很长的值表(存储在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 />");
}

2 个答案:

答案 0 :(得分:5)

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

select pid,count(*)
  from theTable
 group by pid
 order by count(*) desc

只是一个想法...

答案 1 :(得分:0)

为什么在最后一个foreach中使用数组键和值作为$ tabulation的键? 这应该有用......

$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] ))
      $tabulation[$pid] = 1;
    //if this post is already in the tabulation array, incrment its click value by 1
    else
      $tabulation[$pid]++;
}

arsort($tabulation);
$highestClicksValue = reset($tabulation);
$highestClicksPID = key($tabulation);
foreach ($tabulation as $pid => $clicks){
    print("PID: ". $pid . " clicks: " . $clicks . "<br />");
}