Forum Moderators: coopster
[0] => trees
[1] => redwoods
[2] => evergreens Now I want to compare these POSTed tags with existing tags in a MySQL table. I do a fairly typical operation, selecting the 'Tags' table and making it into an array:
$result= mysql_query ("SELECT * FROM Tags") or die(mysql_error());
for($i = 0; $sqlarray[$i] = mysql_fetch_assoc($result); $i++) ; This will leave me with a multidimensional array that has both my tag ID's (which I will need later), and the text of tag. This array might look like this:
(
[0] => Array
(
[tag_id] => 35
[tag_text] => lawncover
)
[1] => Array
(
[tag_id] => 36
[tag_text] => redwoods
)
[2] => Array
(
[tag_id] => 37
[tag_text] => tacobell
)
) And so forth. So I want to compare values in the two arrays and find the common "redwoods" value, but the arrays are in these different formats, as a natural result of a mysql query (multidimensional). This means the comparison tools array_interesect and array_diff don't seem to work. I've been looking around and wondered what people here have done to overcome this in order to successfully compare values in different array formats. Thanks.
for($i = 0; $sqlarray[$i] = mysql_fetch_assoc($result); $i++) {
for($ii=0; $ii<count($needle); $ii++) {
if(stripos($sqlarray[$i][tag_text],$needle[$ii])) {
echo "found"; break;
}
}
}
I'm not sure about your need to match case or not, so you could theoretically use == or strpos if you know the case will be the same.
The above should work or be close.
I didn't appear to need strpos as I had already lowercased. So, the entire solution, coming from the the posted tags and displaying any matches, worked something like this:
//from POST action
$formarray=strtolower ($_POST['tags']);
$formarray=ltrim ($formarray);
$formarray=explode (" ", $formarray);
//from MySQL query
$dbhandle = mysql_connect(localhost, foo)or die("Unable to connect to MySQL");
$selected = mysql_select_db("foo",$dbhandle) or die("Could not select database");
$result= mysql_query ("SELECT * FROM Tags") or die(mysql_error());
// Put MYSQL tags in array, commpare with POSTed tags
for($i = 0; $sqlarray[$i] = mysql_fetch_assoc($result); $i++) {
for ($ii=0;$ii<count($formarray); $ii++){
if ($sqlarray[$i]['tag_text'] == $formarray[$ii]){
// print
echo '<pre>';
print_r ($sqlarray[$i]['tag_text']);
echo '</pre>';
}
}
}
IMO: Always avoid foreach, unless you absolutely need it for some reason.
Also: Make sure you are either 'scrubbing' your POSTed variables with a regular expression, or at the very least using addslashes()...
$formarray=strtolower (addslashes($_POST['tags']));