Count()返回1,逗号分隔的字符串带有爆炸 [英] Count() returning 1 with comma separated string with explode

查看:114
本文介绍了Count()返回1,逗号分隔的字符串带有爆炸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a field that stores tags comma seperated. I'm trying to count the number of items listed.

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

Let's say I've already pulled the data from the DB, and the $tags variable has the following info:

$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变量可以有任意数量的项目-从空到单个项目(例如视频)到多个项目视频,游戏,商店等。

That always returns "1", regardless if there's an item in the array or not. the $tags variable can have any number of items - from empty, to a single item like "Videos" to multiple items "Videos,Games,Store" etc.

可以有人帮我解决我做错的事吗?

Can someone help me out on what I'm doing wrong?

推荐答案

来自PHP手册:

如果定界符包含字符串中未包含的值并且使用了负数限制,则将返回一个空数组,否则将返回一个包含字符串的数组。

If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

因此,简单地-如果在字符串中未找到定界符,则爆炸不执行任何操作。。如果您的变量包含空字符串,count()将返回1。 您需要count()的NULL值返回0。

So, simply - if delimiter is not found in string, explode do nothing. If Your variable contains empty string, count() will return 1. You need NULL value for count() to return 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);

这篇关于Count()返回1,逗号分隔的字符串带有爆炸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆