【问题标题】:Count() returning 1 with comma separated string with explode [duplicate]Count() 返回 1 用逗号分隔的字符串和爆炸 [重复]
【发布时间】:2011-11-10 23:32:30
【问题描述】:

我有一个以逗号分隔的存储标签的字段。我正在尝试计算列出的项目数量。

假设我已经从数据库中提取了数据,并且 $tags 变量具有以下信息:

$tags = "Videos,Magazines,Store";

// First separate tags by commas, put into into array
$tagArray = explode(",",$tags);

// Count how many items are in the array
$arrayCount = count($tagArray);

无论数组中是否有项目,它总是返回“1”。 $tags 变量可以包含任意数量的项目 - 从空的项目到“视频”等单个项目,再到“视频、游戏、商店”等多个项目。

有人可以帮我解决我做错了什么吗?

【问题讨论】:

  • 返回 3 for me。你是 accidentally calling count() 在原始字符串上吗?
  • 不可重现。请发布您的实际代码。 (也许避免混合大小写的变量名。)
  • 编码问题?你的逗号不是逗号吗?
  • 您给我们的确切代码是正确的codepad.org/GnU9hoxI
  • 谢谢。你们是对的,这段代码没有问题,只是我后来使用它的方式。

标签: php count explode


【解决方案1】:

来自 PHP 手册:

如果 delimiter 包含字符串中不包含的值且使用负数限制,则返回空数组,否则返回包含字符串的数组。

所以,简单地说——如果在字符串中没有找到分隔符,爆炸什么也不做。如果你的变量包含空字符串,count() 将返回 1。你需要 NULL 值作为 count( ) 返回 0。

试试这个:

    $tags = "Videos,Magazines,Store";

    // First separate tags by commas, put into into array
$tagArray = ($tags != '')?explode(",",$tags):NULL; // Count how many items are in the array
$arrayCount = count($tagArray);

【讨论】:

  • 依靠 NULL 生成警告。使用 array() 代替
【解决方案2】:

您的代码运行良好,它按预期返回 3,因为您提供了正确的输入字符串来运行代码,但是当您将数据库字段的值分配给$tags,因为它也可以包含 empty string 正如您在问题中所说的那样。

正如您所说,db 字段中的标签可以是零个或多于零个,所以当$tags 不包含标签或空字符串时,如 php explode() 函数手册所述:

如果 delimiter 包含一个不包含在 string 中的值,则 包含类似 [ " " ] 的字符串的数组将被返回。

所以当你的$tags包含空字符串然后explode()返回包含空字符串的数组,所以现在你的$tagArray=[""],在爆炸后你正在使用@987654328 @函数,所以按照php manual of count()

返回array_or_countable 中的元素个数。 当参数既不是数组也不是实现了Countable接口的对象时,返回1。有一个例外,如果array_or_countable为NULL,则返回0

所以因为您的$tagArray 不是 NULL 而是 $tagArray=[""],所以 count($tagArray) 正在返回一个。

所以要解决它,请使用以下代码:

$tags = "Videos,Magazines,Store";
// it can also contains empty string like $tags = ""
$arrayCount = ($tags)?count(explode(",",$tags)):0;
//here $arrayCount will have 3 as expected, But if your $tags contains empty string it will return 0 instead of 1.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-31
    • 2023-03-14
    • 1970-01-01
    • 2016-12-04
    • 2017-01-14
    • 2013-09-30
    • 2012-02-15
    • 2023-04-09
    相关资源
    最近更新 更多