Jump to content

[SOLVED] Counting the same items in an array


ikebaldo

Recommended Posts

Hi, im new here and im a bit of a n00b at php :) .

 

I am trying to count how many times a certain peice of data appears in a database.

 

I have read some data into an array from an sql database, and it has been sorted by name alphabetically.

 

I am attempting to use the following code to display how many of each item there are.

 

$records =@mysql_fetch_array($query_countResults);//stores the data from the query in an array, sorted by name.

 

$temp = 1; //keeps hold of the number of search items as it counts

$check1 = 0; //stores the reference to the first items location in the array

$check2 = 1; //stores the reference to the second items location in the array

 

while($check2 <= $number_results) {

if ($records[$check1] == $records[$check2]){

$temp = $temp + 1;

}else{

echo $temp;

$temp = 1;

}

$check1 = $check1 + 1;

$check2 = $check2 + 1;

}

 

 

this code doesnt currently display items into a table, i am hoping to do that after i have ensured that the loops are working correctly.

 

 

Please help...

 

I wonder if this helps you. If you want to count the number of times a value (for example name) appears you can use this SQL:

 

SELECT `name`, COUNT(`name`) AS n FROM mytable GROUP BY `name`

Thanks for the idea, but im making a list of items with how many each appears in the database, so that wouldnt work.

 

Thank you though

 

What do you mean? That query format will return exactly what you just stated. Just modify the query for the item name and it will return a list of all the items and the number of times each item exists in the table.

Thanks for the idea, but im making a list of items with how many each appears in the database, so that wouldnt work.

 

Thank you though

 

I fail to understand, why ask for help then reject it? Just wastes our time. (your username is noted)

Hi, i'm sorry. I assumed that that SQL statement would only count how many items in total were in the array.

 

I have run that query, and saved the results in the array $records. I have this code to output the results :

$temp = 0;

while($temp <= $number_results){

echo $records[$temp];

}

It doesnt diplay any results at all.

 

Please help, i will actually listen 100% this time!!!!

you will need to substitute your table and column names:

 

<?php

$sql = "SELECT `name`, COUNT(*) as num 
	FROM tablename 
	GROUP BY `name`";
$res = mysql_query ($sql);
while (list($name, $num) = mysql_fetch_row($res))
{
echo "$name : $num <br/>";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.