php 用PHP检查逗号分隔的字符串中是否存在值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13539131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if value exists in comma separated string with PHP
提问by kuttypraba
I need to check if my id exists in comma separated string.
我需要检查我的 id 是否存在于逗号分隔的字符串中。
My string is saved as "1,2,3,4,10"in database.
我的字符串保存"1,2,3,4,10"在数据库中。
I have tried
我试过了
$HiddenProducts = array($sqlvalue);
if (in_array(2, $HiddenProducts)) {
echo "Available";
} else {
echo "Not available";
}
It is not working. Any solutions please...
它不工作。有什么解决办法请...
回答by Decent Dabbler
Use explode()to create an array of string parts from a string, by splitting it by a certain delimiter (in this case a comma).
用于explode()从字符串创建字符串部分的数组,方法是用某个定界符(在本例中为逗号)拆分它。
$HiddenProducts = explode(',',$sqlvalue);
if (in_array(2, $HiddenProducts)) {
echo "Available";
} else {
echo "Not available";
}
回答by Brad
in_array()is in fact what you want, but you are creating your array incorrectly.
in_array()实际上是您想要的,但是您错误地创建了数组。
Assuming $sqlvalue = '1,2,3,4,10'...
假设$sqlvalue = '1,2,3,4,10'...
$hiddenProducts = explode(',', $sqlvalue);
Then you can use in_array().
然后你可以使用in_array().
回答by Tapas Pal
first using explode function convert the comma-separated string in to array
首先使用explode函数将逗号分隔的字符串转换为数组
$HiddenProducts = explode(',',$sqlvalue);
then use in_array function to check
然后使用 in_array 函数来检查
if (in_array(2, $HiddenProducts))
echo "Available";
else
echo "Not available";
回答by phant0m
Instead of merely curing the symptom, let me offer a different approach.
让我提供一种不同的方法,而不是仅仅治愈症状。
You should probably notstore your information in the table like that. It should be possible to let the database figure out, if some product is hidden or not. For that, you need to normalize your data properly.
您可能不应该像那样将信息存储在表中。应该可以让数据库弄清楚是否隐藏了某些产品。为此,您需要正确规范化您的数据。
Apparently, you have a table of products somewhere and some should be hidden. If this is a property trueor falsethat belongs to every product, you can just add it to the your products table as a new column.
显然,您在某处有一张产品表,有些应该隐藏。如果这是一个属性true或false属于每个产品,您可以将它作为新列添加到您的产品表中。
SELECT id FROM products WHERE id = 2 AND hidden = 1
If hiddenis not an intrinsic property of your products, you can also create a helper table that is simply a list of product IDs.
如果hidden不是您产品的固有属性,您还可以创建一个简单的产品 ID 列表的帮助表。
An entry simply says that the product is hidden. If an ID is absent from the table, it's nothidden.
一个条目只是说该产品是隐藏的。如果表中没有 ID,则它不会被隐藏。

