Reputation: 43
I am trying to go from a 1D array that is like array = ("apple", "apple", "banana", "apple") to a 2d array with Array = ("apple", 3), ("banana", 1)
I have the following code which keeps returning 0. Where am I going wrong?
$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);
}
}
}
Upvotes: 0
Views: 118
Reputation: 3002
You can do all of this with a simple sql query where you join this two tables and group by ActivityCategory
(from your example I think that's the key that you want to group by, is not change with what you want).
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
After you run this query you will have two columns. In first you have the activity category and on second the count. I think you manage to move this to the array structure you like.
Also change your mysql connection/query to PDO because you are using old deprecated methods.
Upvotes: 2