开发者

PHP, how can I produce a string, a unique list of values up to three items, for use after IN in a query?

I need to produce a string for use in an query e.g.

SELECT whatever from Keywords.word IN (here);

At the moment I have string which could be

$search = "one word or four";

or

$search = "one";

or

$search = "one one";

I need to validate this into some acceptable for my query. I want a unique list of words, separated with a comma up to a maximum of three.

This is what I have so far.

$array = explode(" ",$search);
$unique = array_unique ($array开发者_运维知识库);

I'm sure there must be a quicker way than evaluating each of the items for blank and selecting the first three.


You could use some array functions, like this:

$arr   = explode(" ", $search);                   // explode into chunks
$uniq  = array_unique($arr);                      // make sure chunks are unique
$three = array_slice($uniq, 0, 3);                // take first three chunks
$in    = sprintf("'%s'", implode("','", $three)); // produces 'first','second','third'

Of course you can do that in one line:

$in = sprintf("'%s'", implode("','", array_slice(array_unique(explode(" ", $search)), 0, 3)));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜