开发者

split array values when there is a comma

i'm able to split a string into an array

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

RESULT 

Array ( [0] =开发者_JS百科> 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


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: What is Normalisation (or Normalization)? )

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜