Home > Backend Development > PHP Tutorial > 怎么判断字符串中值的类型并将其转换成对应变量类型 例'12.1','10', 'string'->12.1,10,'string'

怎么判断字符串中值的类型并将其转换成对应变量类型 例'12.1','10', 'string'->12.1,10,'string'

WBOY
Release: 2016-06-13 13:47:10
Original
788 people have browsed it

如何判断字符串中值的类型并将其转换成对应变量类型 例'12.1','10', 'string'->12.1,10,'string'
如何判断字符串中值的类型并将其转换成对应变量类型。
比如有个变量$a = array('12.1','10','string');要将其变成array(12.1,10,'string'); 该怎么做?
我用eval函数做了下,会出现警告,虽然可以用@抑制住,终究不是什么好办法,难道要用正则?

我转类型是用来将数据插入到数据库里的。数据库有什么办法做这方面转换不(我数据库知识很烂)?
各位高手支点高招吧。
下面是我用eval函数做的的代码

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
$a = array("12.1","10","sting");
foreach ($a as $t)
{
    eval("\$t = $t;");
    var_dump($t);
    echo '<br>';
}
Copy after login




------解决方案--------------------
我也是初学者,根据刚学到的点点知识,试编了个段代码,看是不是你所想要的:
$a=array("12","10.8","string");
foreach($a as $key=>$value)
echo $value.':'.gettype($value).'
';
function changetype(&$value)
{
if (is_numeric($value)){
if (strstr($value,'.'))
settype($value,'double');
else
settype($value,'integer');
}
}
array_walk($a,'changetype');
foreach($a as $key=>$value)
echo $value.':'.gettype($value).'
';
?>
运行结果显示如下:
12:string
10.8:string
string:string
12:integer
10.8:double
string:string
――――――――――
------解决方案--------------------
/*** 给传入的数据赋予正确的类型 **/
function format(&$v) {
if(is_array($v)) {
$v = array_map('format', $v);
}
if(is_numeric($v)) $v += 0;
return $v;
}

$a = array("12.1","10","sting");
var_dump($a);
format($a);
var_dump($a);

执行前
array(3) {
[0]=>
string(4) "12.1"
[1]=>
string(2) "10"
[2]=>
string(5) "sting"
}
执行后
array(3) {
[0]=>
float(12.1)
[1]=>
int(10)
[2]=>
string(5) "sting"
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template