欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

字符串转化为数字?该如何解决

程序员文章站 2024-02-10 16:13:46
...
字符串转化为数字???
今天遇到个比较奇怪的现象,很可能是我储备还不够吧,包含引号的数字的字符串转化为数字时出现了问题


"1000","902865066306","02865066306","SIP Phone","IP Trunk","","trunk20","ON2OFF","1333230069","1333230072","1333230134","65","62","Connected"

上面的为一段数据,接下来操作

$arr = '"1000","902865066306","02865066306","SIP Phone","IP Trunk","","trunk20","ON2OFF","1333230069","1333230072","1333230134","65","62","Connected"';
$arr = explode(',',$arr);
print_r($arr);

打印

Array
(
[0] => "1000"
[1] => "902865066306"
[2] => "02865066306"
[3] => "SIP Phone"
[4] => "IP Trunk"
[5] => ""
[6] => "trunk20"
[7] => "ON2OFF"
[8] => "1333230069"
[9] => "1333230072"
[10] => "1333230134"
[11] => "65"
[12] => "62"
[13] => "Connected"
)

我想把数组里的第九个拿出来来和其他的数据比较,平常把引号包围的字符串转为数字时就是在后面加个0就ok了,可是,今天不一样了

echo $arr[8] + 0; //结果为0

我就纳闷了,怎么会为0呢,$arr[8]明明有值啊,于是我又测试了下

$num = "1333230069";
echo $num+0;//1333230069

弄了好久没明白怎么回事,后来就用了两个办法解决了,一个是用正则把数字提出来,另一个是一开始就把字符串里的双引号全都替换为空。

可是疑惑还没有解决,啰嗦到现在,就是想问问大大们,为什么上面的做法会出现0的结果,而不是想要的数字。

------解决方案--------------------
var_dump($arr[8]); //string(12) ""1333230069""
var_dump($num); //string(10) "1333230069"

这样看就清楚了,将 $arr[8] 的首尾双引号去掉后再运算就对了。
------解决方案--------------------
$a=str_getcsv($arr);
var_dump($a[8]);


------解决方案--------------------
根据你提供的信息我自己也测试了下:
$arr= Array
(0 => "1000",
1 => "902865066306",
2 => "02865066306",
3 => "SIP Phone",
4 => "IP Trunk",
5 => "",
6 => "trunk20",
7 => "ON2OFF",
8 => "1333230069",
9 => "1333230072",
10 => "1333230134",
11 => "65",
12 => "62",
13 => "Connected"
);
echo gettype($arr[8])."
";
echo $arr[8]."
";
$str1=$arr[8]+0;
echo gettype($str1)."
";
echo ($str1)."
";

$num = "1333230069";
$num1=($num+0);
echo gettype($num)."
";
echo gettype($num1)."
";
echo $num1;

?>


输出结果是:
string
1333230069
integer
1333230069
string
integer
1333230069

发现没有出现楼主的问题。
------解决方案--------------------
没必要那么麻烦吧?
$arr = '"1000","902865066306","02865066306","SIP Phone","IP Trunk","","trunk20","ON2OFF","1333230069","1333230072","1333230134","65","62","Connected"';
字符串转化为数字?该如何解决

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频