Mysql Results and array manipulation - php

I am stuck working on a problem, and would appreciate some guidance. I am working with an old system that was coded awfully, and didnt do any validating, or sanitzing of user input, so the database I'm working with is a bit missy.
I have issues with one column called "tags", used for tags for articles. But each row appears like this, and varies between them:
tag tag1 tag2 tag3
OR
tag1, tag2, tag
But I need to combine them and put them into an array that lists them by how many times each one occurs, like this:
tag(2)
tag1(2)
tag2(2)
tag3(1)
Because I'm not the most astute with php, Im not sure if I am going about the problem correctly?
Im new to manipulating arrays on this scale which is why I am stuck at this point. You can view the example below of what I am doing below:
$sql = "SELECT tags, approved FROM articles WHERE approved = '1' ";
$result = mysql_query($sql);
while( $rows = mysql_fetch_array($result) ) {
$arr = $rows['tags'];
$arr = str_replace(", ", " ", $arr); // attempting to clean up the data, so that each word appends with a space.
$arr = str_replace(" ", " ", $arr);
// Don't know what to do next, or if this is even the right way to do it.
}
Any help is appreciated.
Thanks, Lea

Maybe this will be helpful. Modified your code to have a $tagArr for each query. If you need an overall array of tags it would be a bit different, but could easily be coded using the following.
while( $rows = mysql_fetch_array($result) ) {
$arr = $rows['tags'];
$arr = str_replace(", ", " ", $arr); // attempting to clean up the data, so that each word appends with a space.
// Don't know what to do next, or if this is even the right way to do it.
$tagArr = array();
$current_tags = explode(" ", $arr);
foreach($current_tags as $tag) {
if(!array_key_exists($tag, $tagArr)) {
$tagArr[$tag] = 1;
} else {
$tagArr[$tag] = $tagArr[$tag]++;
}
}
// now $tagArr has the tag name as it's key, and the number of occurrences as it's value
foreach($tagArr as $tag => $occurrences) {
echo $tag . '(' . $occurrences . ')<br />';
}
}

Related

PHP compare two arrays from different locations

I am wanting to compare two different arrays. Basically I have a database with phrases in and on my website I have a search function where the user types in a phrase.
When they click search I have a PHP page which 'explodes' the string typed in by the user and its put into an array.
Then I pull all the phrases from my database where I have also used the 'explode' function and split all the words into an array.
I now want to compare all the arrays to find close matches with 3 or more words matching each phrase.
How do I do this?
Well what I've tried totally failed, but here is what I have
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //user entered data
$search_term = str_replace ("?", "", $search_term); //removes question marks
$array = explode(" ", $search_term); //breaks apart user entered data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array) . " LIMIT 0,10";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title'];
$thetitle = str_replace ("?", "", $thetitle);
$title_array[] = $thetitle;
$newarray = explode(" ", $search_term);
foreach ($newarray as $key=>$newword) {
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value);
$contacts = array_diff_key($thenewarray, array_flip($newarray));
foreach($contacts as $key => $value) {
echo $newword."<br />";
echo $value."<br /><hr />";
}
}
}
But basically all I want is to display suggested phrases which are similar to what the user has already typed into the search box.
So If I searched "How do I compare two arrays that have the same values?", I would see 10 suggestions that are worded similar, so like "How to compare multiple arrays?" or "can I compare two arrays" etc...
So basically like when I first posted this question on this site, I got other questions that may help, thats basically what I want. This code im using was origionally to match just one word or an exact matching string, im editing it to find matching words and only show phrases with 3 or more matching words.
I don't think that this is the best solution for your search script. But I'll try to give you the answer:
<?php
$string1 = "This is my first string";
$string2 = "And here is my second string";
$array1 = explode(" ", $string1);
$array2 = explode(" ", $string2);
$num = 0;
foreach($array1 as $arr) {
if(in_array($arr, $array2))
$num++;
}
$match = $num >= 3 ? true : false;
?>
use array_intersect function
$firstArray = "This is a test only";
$secondArray = "This is test";
$array1 = explode(" ", $firstArray);
$array2 = explode(" ", $secondArray);
$result = array_intersect($array1, $array2);
$noOfWordMatch = count($result);
$check = $noOfWordMatch >= 3 ? true : false; ;

Picking numbers in an order

I had a task to slide images from a mysql database using jquery slide and not the animation scripts. The slide is supposed to show at least the most recent ten images that was uploaded. With that I first of all wrote a random query
mysql_query("select * from tblname order by rand() limit 1);
But as expected, it picks the images at random irrespective of when it was posted and of course it wasn't the most recent ten. After some thought I now had to first run a query to get the most recent ten
mysql_query("select * from tblname order by ID limit 10);
while($row=mysql_fetch_array($sql){
$slideid=$slideid.",".$row['recordid'];
}
this of course results to a variable of this order
$var="23,22,24,34,27,78,56,87,98,55";
I tried handling it like an array but it wasn't giving any positive result, hence I had an issue of how to pick this numbers and use it for the slide
$myArr=explode(',',$var);
sort($myArr);
for($i=0;$i<count($myArr);$i++)
{
echo $myArr[$i];
}
Edit: For better efficiency use:
$myArr=explode(',',$var);
sort($myArr);
foreach ($myArr as $val)
{
echo $val;
// Or do whatever else you want with each one.
}
Edit 2: See comments below on efficiency vs for loops vs unexpected results. :)
Based on your comments I will offer my 2p into the mix
this is what I did $slideid="23,22,24,34,27,78,56,87,98,55"; $arr =
explode(',',$slideid); foreach ($arr as $val) { //lets get the
variables from the form post $rs = mysql_query("SELECT * FROM tblname
WHERE id='$val'") or die(mysql_error());
while($row=mysql_fetch_array($rs)){ echo "<img src='image/$image'>"; }
} the images are displayed one by one using jquery slide
Now I think we are wasting time dealing with exploding this variable because mysql has the nifty IN() function (possibly in other db's I don't know)
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid})") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}
I hope this helps
$var="23,22,24,34,27,78,56,87,98,55";
$arr = explode(',',$var);
foreach ($arr as $val) {
// work with $val
}
explode splits the string to an array
1) Explode the string into an array, splitting on the comma.
2) You didn't say whether you wanted to re-order the numbers into numerical order, or process them in the order they're already in. If the former, sort the array with sort($arr);
3) Loop over the array in sequence and do something with each number
$str = '1,2,3,4,5,6';
$arr = explode(',', $str);
foreach($arr as $num) echo $num.'<br />';
Note if there is any change of spaces after commas, a better choice would be preg_split rather than explode, as this is more dynamic.
$arr = preg_split('/, ?/', $str);
You can achieve this using php explode function
$pieces = explode(",", $var);
echo $pieces[0]; // piece1
echo $pieces1; // piece2
.
.
.
echo $pieces[n]; // piece n
I think you need to get result of order with respect to order of variable here
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid}) ORDER BY FIELD(id, {$slideid}) ") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}

Remove last comma or prevent it from being printed at all MySQL/PHP

I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?
I did try to use rtrim, but I did not probably do it right.
This is my code as it is today:
<?php
$query0 = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()";
$result0 = mysql_query($query0);
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keyword = $row0['LCASE(ord)'];
echo "$keyword, ";
?>
I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )
$keyword = $row0['LCASE(ord)'];
$keywordc = "$keyword, ";
$keyword- = rtrim($keywordc, ', ');
echo "$keyword-, ";
As you might imagine, this did not print much (but at least it did not leave me with a blank page...)
I would do:
$keywords = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keywords[] = $row0['LCASE(ord)'];
}
echo implode(',', $keywords);
I usually do this by placing the results in an array first
$some_array = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {
$some_array[] = $row0['LCASE(ord)'];
}
then simply:
echo "My List: " . implode(', ', $some_array);
// Output looks something like:
My List: ord1, ord2, ord3, ord4
substr($string, 0, -1);
That removes the last character.

How to handle my data?

Edit: The aim of my method is to delete a value from a string in a database.
I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:
str_replace($pid . ",","",$boom);
$pid is a page id, eg 40
$boom is an exploded array
If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:
,56,12
When I have the concat in the str_replace it doesnt do a thing. Is this possible?
Answering your question: yes you can. That code works as you would expect it to.
But this approach is wrong. It will not work for $pid = 12; (last element, without trailing coma) and will incorrectly replace 40, in $boom = '140,20,12';
You should keep it in array, search for unwanted value, if found unset it from the array and then implode with coma.
$boom = array_filter($boom);
$key = array_search($pid, $boom);
if($key !== false){
unset($boom[$key]);
}
$boom = implode(',',$boom);
[+] Your code does not work because $boom is an array, and str_replace operates on string.
As $boom is an array, you don't need to use array on your case.
Change this
$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);
to
$together = str_replace($pid . ",","",$ticket_array);
Update: If you want still want to use array
$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:
$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
unset($boom[$r]);
}
Old question:
Can you concatenate inside a str_replace like this: ... ?
Yes you can, see the example:
$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));
Result:
Array
(
[0] => 56,12
)
Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.
It might be easier for you if you're unsure to create a variable first:
$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));
You should store your "ticket array" in a separate table.
And use regular SQL queries (UPDATE, DELETE) to manipulate it.
A relational word in the name of your database is for the reason. And you are abusing this smart software with such a barbaric approach.
You could use str_split, it converts a string to an array, then with a foreach loop echo all the values except the first one.
$numbers_string="40,56,12";
$numbers_array = str_split($numbers_string);
//then, when you have the array of numbers, you could echo every number except the first separating them with a comma
foreach ($numbers_array as $key => $value) {
if ($key > 0) {
echo $value . ", ";
}
}
If you want is to skip a value not by it's position in the array, but for it's value then you could do this instead:
$unwanted_value="40";
foreach ($numbers_array as $key => $value) {
if ($value != $unwanted_value) {
echo $value . ", ";
}
else {
unset($numbers_array[$key]);
$numbers_array = array_values($numbers_array);
var_dump($numbers_array);
}
}

php only get the first occurrence of a word from an array

I have an array of tags that I'm pulling from a database, I am exporting the tags out into a tag cloud. I'm stuck on getting only the first instance of the word. For example:
$string = "test,test,tag,tag2,tag3";
$getTags = explode("," , $string);
foreach ($getTags as $tag ){
echo($tag);
}
This would output the test tag twice. at first i thought i could use stristr to do something like:
foreach ($getTags as $tag ){
$tag= stristr($tag , $tag);
echo($tag);
}
This is obviously silly logic and doesn't work, stristr seems to only replace the first occurrence so something like "test 123" would only get rid of the "test" and would return "123" I've seen this can also be done with regex but I haven't found a dynamic exmaple of that.
Thanks,
Brooke
Edit: unique_array() works if I'm using a static string but won't work with the data from the database because I'm using a while loop to get each rows data.
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
if ($getTag_data)
{
while ($rowTags = mysql_fetch_assoc($getTag_data))
{
$getTags = array_unique(explode("," , $rowTags['tags']));
foreach ($getTags as $tag ){
echo ($tag);
}
}
}
use array_unique()
$string = "test,test,tag,tag2,tag3";
$getTags = array_unique(explode("," , $string));
foreach ($getTags as $tag ){
echo($tag);
}
Use your words as keys to the dictionary, not as values.
$allWords=array()
foreach(explode("," , $string) as $word)
$allWords[$word]=true;
//now you can extract these keys to a regular array if you want to
$allWords=array_keys($allWords);
While you are at it, you can also count them!
$wordCounters=array()
foreach(explode("," , $string) as $word)
{
if (array_key_exists($word,$wordCounters))
$wordCounters[$word]++;
else
$wordCounters=1;
}
//word list:
$wordList=array_keys($wordCounters);
//counter for some word:
echo $wordCounters['test'];
I'm assuming that each row in your table contains more than one tag, separated by coma, like this:
Row0: php, regex, stackoverflow
Row1: php, variables, scope
Row2: c#, regex
If that's the case, try this:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
//fetch all the tags you found and place it into an array (with duplicated entries)
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
array_merge($getTags, explode("," , $row['tags']);
}
}
//clean up duplicity
$getTags = array_unique($getTags);
//display
foreach ($getTags as $tag ) {
echo ($tag);
}
I'd point out that this is not efficient.
Another option (already mentioned here) would be to use the tags as array keys, with the advantage of being able to count them easily.
You could do it like this:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
$tags = explode("," , $row['tags']);
foreach($tags as $t) {
$getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1;
}
}
}
//display
foreach ($getTags as $tag => $count) {
echo "$tag ($count times)";
}
please keep in mind none of this code was tested, it's just so you get the idea.
I believe php's array_unique is what you are looking for:
http://php.net/manual/en/function.array-unique.php
Use the array_unique function before iterating over the array? It removes every duplicate string and return the unique functions.

Categories