在php中计算逗号分隔的值,如何? [英] Counting comma separated values in php, how to?

查看:85
本文介绍了在php中计算逗号分隔的值,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量保持值用逗号(Implode)分隔,我想获得该变量的值的总数,但count()只是返回1.

I have a variable holding values separated by a comma (Implode), I'm trying to get the total count of the values in that variable however, count() is just returning 1.

我已经尝试将逗号分隔的值转换为一个正确格式的数组,仍然吐出1。

I've tried converting the comma separated values to a properly formatted array which still spits out1.

因此,可以看到sarray会话等于value1,value2,value3的快速代码段:

So heres the quick snippet where the sarray session equals to value1,value2,value3:

$schools = $_SESSION['sarray'];
$result = count($schools);

任何帮助将不胜感激。

Any help would be appreciated.

推荐答案

您需要 explode $ schools 转换为实际数组:

You need to explode $schools into an actual array:

$schools = $_SESSION['sarray'];
$schools_array = explode(",", $schools);
$result = count($schools_array);

如果你只需要计数,并且100%确定它是一个干净的逗号分隔的列表,还可以使用 substr_count(),这可能会稍微快一点,更重要的是,对于非常大的数据集,内存更容易:

if you just need the count, and are 100% sure it's a clean comma separated list, you could also use substr_count() which may be marginally faster and, more importantly, easier on memory with very large sets of data:

$result = substr_count( $_SESSION['sarray'], ",") +1; 
 // add 1 if list is always a,b,c;

这篇关于在php中计算逗号分隔的值,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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