0

I'm using php and mysql. I'm having a problem with my piece of code. I want to remove duplicates and output the unique ones.

.php code

$query = "SELECT * FROM blog_posts";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo  $row['post_category'];
echo array_unique(explode(',', $var));

the table:

id(1) = post_category(CategoryA)
id(2) = post_category(CategoryB)
id(3) = post_category(CategoryC)
id(4) = post_category(CategoryA, CategoryB)
id(5) = post_category(CategoryB, CategoryC)

I'm about to create dynamic url links to every category

5
  • do you want to remove duplicate array values? Commented Dec 11, 2013 at 5:29
  • Yes sir. But it returns "CategoryACategoryBCategoryCCategoryA,CategoryBCategoryB,CategoryC value =/ Commented Dec 11, 2013 at 5:30
  • Have you tried out array_unique() function? Commented Dec 11, 2013 at 5:31
  • i posted an answer that will remove duplicate values from your array.check it Commented Dec 11, 2013 at 5:31
  • @user3064038 edit your result to your question Commented Dec 11, 2013 at 5:31

3 Answers 3

2

use DISTINCT in your select query.

SELECT DISTINCT post_category FROM blog_posts;

Sign up to request clarification or add additional context in comments.

Comments

0

You may try this

$query = "SELECT DISTINCT post_category FROM blog_posts";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
  $var[] = $row['post_category'];
}
print_r($var);

4 Comments

Works perfectly too. How can I make the output like "Category A Category B Category C" plainly? Without the "Array ( [0] =>" and so on
just implode the array like implode(" ", $var);
That works well too! Thanks alot! Now I've separated them with spaces, how can I make it a link? like this one.. CategoryA = dev/index.php/category=a and so on..
Yeah sure, explode your category with space and make apart "Category" and "A" and use this to make link
0

if you want to get distinct values from your mysql query than use DISTINCT keyword.

and if you want to remove duplicate values from your multidimensional array then:

$type is the multidimensional array.as array-unique wont work for multidimensional arrays.

$type = array_map("unserialize", array_unique(array_map("serialize", $type)));
$type=array_values($type);

2 Comments

I used the DISTINCT. Works perfectly, but how about for the items with two categories? Like id(4) = CategoryA, CategoryB and so on
use explode for this case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.