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...

Link to comment
Share on other sites

 

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.

Link to comment
Share on other sites

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!!!!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.