, separated values in a variable
I have a variable $a = 271,245,789;
<select name="cat" class="main" multiple="multiple">
<option value="">--Select Category--</option>
<?
////////////////display category//////////////////
$cat_details=mysql_query("select category_id,category from category_tb order by category");
while($cat_data=@mysql_fetch_array($cat_details)){?>
<option value="<?=$cat_data['category_id'];?>" <? if($a==$cat_data['category_id']){?> selected="selected"<? } ?>><?=$cat_data['category'];?></optio开发者_如何学运维n>
<? } ?>
</select>
in mysql we have find_in_set for these "," separated values. How can i do this in PHP
Something like this?
if (in_array($value, explode(',', $a)) {
// Found
}
OK, I know now, what FIND_IN_SET()
does
$index = array_search($value, explode(',', $a));
At all with explode()
you can split this CSV-string into its parts and then apply every array
-function on it.
You can do this like that ($key
is the position of the $value
within $your_string
):
$key = array_search((string)$your_value, explode(',', $your_string));
See documentation for array_search() and explode().
As alternative to the in_array/explode workaround you could also test with:
function find_in_set($set, $value) {
return strstr(",$set,", ",$value,");
}
Either way I would separate that out; your template is convoluted enough already. (You should really move the mysql_query out too, and provide a wrapper function which simply returns a list instead.)
精彩评论