问题
I have been looking for an answer for this, but none seem to actually help my specific situation. I'm trying to post a list of words and then remove the duplicate data (words) that come from the form.
For some reason I can't seem to get array_unique to work. PHP keeps giving me errors saying my post array is a string. But if I try using explode, it says I'm using an array. Really confused right now and very frustrated.
My code is simple:
if(!empty($_POST['keywords']))
{
$posted = $_POST['keywords'];
$posted = array_unique($posted);
echo $posted;
}
I'm not necessarily looking for an exact answer, but some guidance so I can better understand what I'm doing wrong here.
The form:
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<p>
<textarea name="keywords" rows="20" columns="120"></textarea>
</p>
<p>
<input type="submit" name="submit" />
</p>
</form>
回答1:
Consider first splitting the keywords argument by spaces, then finding the unique values:
$posted = array_unique(explode(' ', str_replace("\n", ' ', $posted)));
回答2:
Maybe you should look into using array_filter
That way you can define your own callback function for maximum rigorousness on your your removes...
http://php.net/manual/en/function.array-filter.php
Also: Have you tried messing around with the array_unique flags?
http://php.net/manual/en/function.array-unique.php
回答3:
Your keywords form field is setup as a textarea, so when you post, you are posting a string. Try this:
$posted = $_POST['keywords'];
$postedKeywords = explode(' ', $posted);
$posted = array_unique($postedKeywords);
回答4:
The previous answers are great, but since the words are being input to a textfield, the delimiter will be unpredictable. Consider using a regular expression instead:
preg_match_all('/([^\s]+)/', $_POST['keywords'], $matches);
$unique_words = array_unique($matches[0]);
来源:https://stackoverflow.com/questions/8514261/remove-duplicate-data-from-post-array