Count Frequency of Tags - php

How can I get the frequency of an item in a field contained in the following array?
//
...
...
//database stuff
while($row=mysql_fetch_array($result))
{
//Retrieve tags for this article
$tags=$row["art_tags"];
$tagarray=explode(",",$tags);
foreach($tagarray as $key => $value)
{
//need solution here
//how to Search entire art_tags field in the database and get frequency of all tags
echo $value;
Eg.
// Rice x 23 times
// Beans x 12 times
}

To count up all the tags in your database use array_count_values():
$all_tags = array();
while ($row = mysql_fetch_assoc($result)) {
$all_tags = array_merge($all_tags, explode(',', $row['art_tags']));
}
$all_tags = array_count_values($all_tags);
echo $all_tags['rice'];
Or, for one just tag, let the database do the work for you with COUNT(*):
$tag = 'rice';
$sql = "SELECT COUNT(*) FROM articles
WHERE art_tags LIKE '$tag'
|| art_tags LIKE '$tag,%'
|| art_tags LIKE '%,$tag'
|| art_tags LIKE '%,$tag,%'";
$result = mysql_query($sql);
list($number) = mysql_fetch_row($result);

One way that you could do this is to use the sql count function. Then you wouldn't need to do this programatically. Though, if you have no control over the query and have to do this in code, you would either have to iterate through the array and check to see if the tag that you are looking for is contained inside each record. Unless the query is already finding only those instances of the tags that you need then just get the size of the array.

you can try this code:
foreach($tagarray as $key => $value
{
$tag_count[$value] += 1;
}
and then:
foreach ($tag_count as $tag => $count)
{
echo $tag.'x'.$count.'times';
}

Related

Combing queries and arraying results

Okay essentially what I'm trying to achieve is to combine the first query with the second one the trouble I'm having is that I'm unable to array out the results from the first query to then use in the second one. Here is my first query what this achieves is that it selects all the room subjects from my users which typically look like this, welcome to my #room hope you #enjoy once is selects one it will then strip the subject of the words and will only keep the hash-tags for example it will keep #room and #enjoy once its goes through and selects all the hash-tags from all of the room subjects it will then order them from how frequent they are used among subjects of all users.
$sql = mysql_query("SELECT subject FROM `users`");
$row = mysql_fetch_array($sql);
$freqDist = [];
foreach($results as $row)
{
$words = explode(" ", $row);
foreach($words as $w)
{
if (array_key_exists($w, $freqDist))
$freqDist[$w]++;
else
$freqDist[$w] = 1;
}
}
arsort($freqDist);
foreach($freqDist as $word => $count)
{
if (strpos($word, '#') !== FALSE)
echo "$word: $count\n";
else
echo "$word: does not contain hashtag, DROPPED\n";
}
Now what I'm trying to achieve here is that I'm trying to array out the results from the above query so then I can perform an action on each hash-tag which is grabbed from above. Below I have included the code and essentially the problem I face lies solely on this line $all = array("hashtag1", "hashtag2", "hashtag3"); as what I'm trying to achieve is instead of typing in directly the hash-tags I want to perform the action on I would want them to be grabbed via using the above query.
$all = array("hashtag1", "hashtag2", "hashtag3");
$trending = $all;
foreach($trending as $tags)
{
$sql = mysql_query("SELECT * FROM `users` WHERE `subject` LIKE '%$tags%'");
$sums = mysql_query("SELECT SUM(viewers) AS viewers FROM `users` WHERE `subject` LIKE '%$tags%'");
$num_rows = mysql_num_rows($sql);
$row = mysql_fetch_assoc($sql);
$sum = mysql_fetch_assoc($sums);
}
So again just to outline my problem I'm trying to grab the results from the first query and use them as an array with the second query. I apologise for the length of this question I just assumed it would help you better understand my question.
As per my understanding, you want to store the hashtag value in an array. if so then just update your foreach()
$hashWord = array();
foreach($freqDist as $word => $count)
{
if (strpos($word, '#') !== FALSE)
echo "$word: $count\n";
$hashWord[] = $word;
else
echo "$word: does not contain hashtag, DROPPED\n";
}

How to remove item on an array on php using mysql database data

I want to do something like this
----sql output----
name TEXT
b
c
$arr = ["a","b","c","d"];
foreach($arr as $key=>$val){
$query = "select count(*) from mydata where name = $val";
$count = xxxx($query);
if($count)unset($arr[$key]);
}
And $arr will be
a,d
Any simple way to do it but not checking every single element?
---edited---
I think I solve my problem myself...getting some inspired from mrlore that using having.
$arr = ["a","b","c","d"]; /* make the string inside arr safe for query */
$val = array_map(function($val){return "'$val'";},$arr);
$q = "select name from mydata where name in (" . implode(',',$val) .")";
$all = xxxxx($q);
$arr = array_diff($arr,$all);
This took me 0.8 second. Using my old way take 46 second and RST way takes 2 seconds.
---edited----
I have over 200k rows of data in my database, so I want a better way to optimize it.
--re MrLore--
ps : I don't know how to use stackoverflow to posting comments..so I just edit my post.
I have tried it on my mysql workbench but it does not seem to work for me.
select name from mydata
where name in("a","b","c","d")
having count(name) = 0
-- returns nothing
select name from mydata
where name in("a","b","c","d")
having count(name) > 0
$arr = ["a","b","c","d"];
$query = "select DISTINCT name from mydata";
$results = <result of query>;
foreach ($results as $result){
if(($key = array_search($result, $arr)) !== false) {
unset($arr[$key]);
}
}
Or the other way around
foreach ($arr as $key=>$value){
if( in_array( $value, $results) ) {
unset($arr[$key]);
}
}
By querying DISTINCT the database only returns unique values. You can then compare them with the array you have and remove them.

PHP Nested Loop. How on the second loop print items according to the id of the first loop?

I need to print a wine list from a database.
I need to print at first a categorie and after all the items that are inside. Thats the order. And i have multiple categorie. So at the end the result will be categorie1, many items, categorie2 many items...
This is the code that i write from now: I think that my problem is to print items according to the id of the alcool_categorie !!
$q_vine = "SELECT * FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
$q_bouteille = "SELECT * FROM alcool_item where ALCNID = '$alid'";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
for($i = 0; $i < $n_vine; $i++){
echo mysql_result($r_vine,$i,'named').'<br/><br/>';
for($z = 0; $k < $n_bouteille; $k++){
echo mysql_result($r_bouteille,$k,'name').'<br/>';
}
}
I think it's best to use a "JOIN" in your query and then order the rows in the way you want them to be ordered, then you'll only need one loop. While running the loop you compare the category name with the previous category name and if it changes display the category name.
Example
$sql = "SELECT categoryName, bottleName FROM category INNER JOIN bottle ON category.categoryId = bottle.categoryId ORDER BY category.categoryId";
$result = mysql_query($sql,$connection);
$categoryName = ''; //just to make sure the first time the Category is named
while ($row = mysql_fetch_assoc($result)) {
if($categoryName != row['categoryName']){
$categoryName = row['categoryName'];
echo '<h1>'.$categoryName.'</h1>';
}
echo row['bottleName'].'<br/>';
}
Try this after correctly giving the category id field name in the query and inside the first while loop.
$q_vine = "SELECT id, named FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
while ($row = mysql_fetch_assoc($r_vine)) {
$categories[$row['id']] = $row;
}
$q_bouteille = "SELECT name, ALCNID FROM alcool_item ";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
while ($row = mysql_fetch_assoc($r_bouteille)) {
$items[$row['ALCNID']] = $row;
}
foreach ($categories as $category_id=>$category) {
echo "<ul><li>{$category['named']}<ul>";
foreach ($items[$category_id] as $item) {
echo "<li>{$item['name']}</li>";
}
echo "</ul></li></ul>";
}
You will want to look into PHP's foreach construct. Foreach loops through an entire array of results, for each element inside the array, it extracts its value and optionally also its key. This will not require the use of mysql_num_rows.
Instead of calling mysql_result, you could use mysql_fetch_assoc to get a row's value from your mysql_query. The row's To get all values, you can incorporate this into a loop even. If you do the latter, you can create your own array of key/value pairs and use this inside a foreach construct.
Also note that the use of mysql is outdated, you will want to use mysqli now, which is very similar to mysql.

Multiple for loops - how to print data

i want to make a website something like popurls.com, but I will use static data stored in MySQL database. Btw I use php/mysql.
In each list i want to show around 10 links (just like on popurls). In that case, if I would have 20 lists, i would need to make 20 'for' loops (for each particular list).
My question is; is there some better way to print that 20 lists instead of using 20 'for' loops in php.
a for loop or a foreach loop will work fine, but it will be a lot less coding if you just create a single for loop and push content into an array of arrays or an array of strings... you can then do whatever you'd like with the actual content (assuming we're grouping by a column category. I'll use an example that uses an array of strings (and the query that I reference is explained here: http://explainextended.com/2009/03/06/advanced-row-sampling/)
$query = mysql_query([QUERY THAT GETS ALL ITEMS, BUT LIMITS BY EACH CATEGORY]) or die(mysql_error());
$all_items = array();
while($row=mysql_fetch_array($query)){
if (!isset($all_items[$row['category']])){ //if it isn't created yet, make it an empty string
$all_items[$row['category']] = "";
}
$all_items[$row['category']] .= "<li><a href='".$row['url']."'>".$row['title]."</a></li>"; //concatinate the new item to this list
}
Now we have an array where the block of HTML for each section is stored in an array keyed by the name of the category. To output each block, just:
echo $all_items['category name'];
PHP's foreach http://php.net/manual/en/control-structures.foreach.php
Depends a lot on your data input but I could imagine something like this:
<?php
$lists = arrray('list1', 'list2', 'list3');
foreach ($lists as $current) {
$data = fetch_data_from_mysql($current);
foreach ($data as $link) {
echo "Link";
}
}
function fetch_data_from_mysql($current)
{
$list_data = array();
// do whatever is required to fetch the list data for item $current from MySQL
// and store the data in $list_data
return $list_data;
}
You just need two foreach loops. Assuming that you take the data from a mysql table (like you wrote), this could be like this:
$list_query = mysql_query("SELECT * FROM lists";)
while( $list = mysql_fetch_array($list_query) )
{
echo "<h1>{$list['title']}</h1>";
$query = mysql_query("SELECT * FROM entries WHERE list_id = {$list['id']}");
while( $entry = mysql_fetch_array($query) )
{
echo "- {$entry['name']}<br />";
}
}
You can get all the information from the database and parse it into an array, something like
array[<news type1>] = array( link1, link2, link3, etc);
array[<news type2>] = array( link1, link2, link3, etc);
and so on
and on the layout you can use
foreach ($newsCategory AS $categoryLinks) {
foreach ($categoryLinks AS $newsLink) {
<show the link and / or extra data>
}
}
Just store your links in two-dimensional array. That way you'll have to make 1 outer loop (iterating over lists) and 1 inner loop iterating over links in a particular list.
$links = array(
'science' => array('link1', 'link2', ...),
'sports' => array('link1', 'link2'),
// ... and so on
);
foreach ($links as $category => $urls) {
echo "Links in category: $category\n";
foreach ($urls as $url) {
echo $url . "\n";
}
}

PHP, SQL, in_array with csv and while loop only retrieving integer

I have searched for similar questions but cannot find the right answer to my specific one. I have a column (data) in my table (table) which contains comma separated values which are id's e.g.
Row 1= 4,5,45
Row 2= 5,8,9
Row 3= 5
I use an in_array function to retrieve the number of occurances for the $data value within the while loop. So I use an sql function to retrieve the number of times a certain value such as '5' occurs in all rows within the while loop.
The issue is that I can only retrieve the $data value if it is by itself (i.e. no commas just the integer by itself) so based on my example in the list, I can only retrieve 5 once (row 3). I would like to retrieve the value '5' three times as it appears in all the rows. Here is my code below and any help would be appreciated. The $selectiontext variable is what the user enters from the form.
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
}
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
Thank you.
you keep overwriting the variables $datacheck and $id, leaving you with only the last version of them. move that curly brace down two lines, like this:
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
}
I am not totally sure of your requirements, is not very clear what you intend to do as part of the code is missing.
I assume you want to check each row of a comma separated of a CSV file ($frnd_arry_mem1 being the row) against your data in column data, if any of those comma separated data (not) occurs.
Assuming you are already looping through your CSV, this would be the code (non tested):
NOTE: might be inefficient retrieving data within a loop, if you can do otherwise - but I cant tell as I dont kow the full specs of your script.
If I got the specs wrong please clarify, I will try to help further.
$sql = "SELECT data, id
FROM table
WHERE data='$selectiontext'";
$sql_frnd_arry_mem1 = mysql_query($sql);
$results = array();
// get values to check
while ($row = mysql_fetch_array($sql_frnd_arry_mem1))
{
$results[] = array(
'datacheck' => $row["data"],
'id' => $row["id"],
);
}
foreach ($results as $result)
{
$frndArryMem1 = explode(",", $frnd_arry_mem1);
$data = explode(',', $result['datacheck']);
foreach ($data as $d)
{
if (($frnd_arry_mem1 !=="") && (!in_array($d, $frndArryMem1)))
{
echo 'DEBUG: Record #' . $id . ' not found, value:' . $d . '</br>';
}
}
}

Categories