views:

104

answers:

1

hi i'm able to split a string into an array

$array  = preg_split("/[\s]*[,][\s]*/", $category); 

RESULT 

Array ( [0] => jquery[1] => bla[2] => bla);

but now i have a database with a row holding all by categories ("cat1, 2, 3, ..") - multiple records have similar categories- so in order to create a quick "category" menu i'm using this code this code:

           while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
        $category[] = $row[category];
}   
    $array = array_unique($category);

as you can imagine the result is like this:

Array ( [0] => bla1,bla2, bla3[1] => bla6, bla4[2] => bla11 ....);

is there a way to slip this array so that (one more time) i get a slip array

i have used the above "array_unique" method but is not working - though all google searches lead me to the same result (being the above one)

hope you could help

thanks

+2  A: 

First of: Splitting a string is easier with the explode() function.

Guessing what you want to do i wrote up a little code sample:

<?php
$dbRows = array("x,y,z", "a,b,c", "y,b,c");

$allCats = array();
foreach($dbRows as $row) {
    $allCats = array_merge($allCats, explode(",", $row));
}

var_dump(array_unique($allCats));

/*
array(6) {
  [0]=> string(1) "x"
  [1]=> string(1) "y"
  [2]=> string(1) "z"
  [3]=> string(1) "a"
  [4]=> string(1) "b"
  [5]=> string(1) "c"
}
*/

so you take out all of the values, fill a big array with those and filter it out at the end.

I hope this is what you are trying to do.


On a sidenote: Just in general it is not considered "good practice" to store stuff in your database that you need to perform string operations on. You might want to only store one value per column to make your live easier.

( See this Stackoverflow question: http://stackoverflow.com/questions/246701/what-is-normalisation-or-normalization-why-is-it-important )

Edit

A shorter version of the above code with the same output:

<?php
$dbRows = array("x,y,z", "a,b,c", "y,b,c");
$allCats = explode(",", implode(",", $dbRows));
var_dump(array_unique($allCats));

this creates one big string ( "x,y,z,a,b,c,y,b,c" ) and splits that one. Left the above example as i'd guess it is easier to read/clearer

edorian
thanks, that is a fantastic answer - it works.the normalization - is something that i tried to use in previous projects, and of course the advantages are clear, but i have no idea why i have not used it here, however, now i'm clad that i when this way simply to ask this question (i hope i will lean in), as i may need to use explode in other projects without the DB.thanks a lot
aurel