计数次数值出现在数组php中

时间:2016-08-17 14:47:48

标签: php arrays

我正试图从像这样的一维数组 array =(“apple”,“apple”,“banana”,“apple”)  用2d阵列 Array =(“apple”,3),(“banana”,1)

我有以下代码继续返回0.我哪里出错?

$result = mysqli_query($con, "SELECT * FROM Entries WHERE Trial=$trial");   
$activities = array(); 
while($row = mysqli_fetch_assoc($result))
{ 
    $activityCatID = $row['Activity']; 
    $resulting = mysqli_query($con,"SELECT ActivityCategory FROM Activity WHERE ActivityID=$activityCatID"); 
    array_push($activities, mysqli_fetch_assoc($resulting));
}

if(sizeof($activities) > 0) 
{       
    $act_and_count = array(); 
    $temp = $activities[0];

    for($ii = 0; $ii < sizeof($activities); $ii++)
    {
        if(!search_array($activities[$ii], $act_and_count))
        {
            $temp = $activities[$ii];               
            $cnt = count(array_filter($activities, create_function('$a', 'return $a==\'' .$temp. '\';')));                          
            $act_and_count[] = array("Activity" => $activities[$ii], "Count" => $cnt);                    
        }      
    }   
}

1 个答案:

答案 0 :(得分:2)

您可以通过一个简单的SQL查询来完成所有这些操作,您可以通过ActivityCategory加入这两个表并进行分组(从您的示例中我认为这是您要分组的键,不是改变你想要的东西。)

SELECT a.ActivityCategory , count(*) as Count FROM Entries e
INNER JOIN Activity a
ON e.Activity = a.ActivityID
WHERE e.Trial=$trial
GROUP BY a.ActivityCategory

运行此查询后,您将有两列。首先,您拥有活动类别,其次是计数。我认为你设法将它移动到你喜欢的数组结构。

还要将您的mysql连接/查询更改为PDO,因为您使用的是旧的弃用方法。