php: count number of times a string appears in an mySql array
* edit * I asked this question as a php question, without the tag of mySql (which has been added by another SO member --> not a big deal to me, but just saying). I am sorry for any confusion the inclusion of the ?extraneous? detail that the array was from a mySql query!
I am hoping to keep the queried data from the SELECT *
to loop through using PHP in an array. I thought, in order to keep this code simple, that PHP could count the number of times a string occurs in a particular position in an array.
* /edit *
I would like to find out how many times a string appears in a particular column from a mySql query result.
For example, lets say I have a table 'automobiles' and their is a column 'type' in that table. The column 'type' has values such as 'sedan', 'van', 'suv' etc.
If I query everything from the table like this:
$query = "SELECT *
FROM automobiles";
and then insert the queried values into an array:
$the_array = mysql_fetch_array($query);
and then try to quantify the number of times a string occurs like this:
$count = array_count_values($the_array);
print_r($count);
not only does this开发者_运维百科 not work, but the data would be inaccurate because the values would be based on the entire table, not on the automobile 'type' column alone.
$query = "SELECT `type`, COUNT(*) `count` FROM `automobiles` GROUP BY `type`";
You can do this with a simple SQL aggregation:
SELECT type, COUNT(*) FROM automobiles GROUP BY type
or you can go
$query = ("SELECT * FROM automobiles WHERE type='TYPE'");
$total_count = mysql_num_rows($query);
echo $total_count;
精彩评论