How to determine the type of a value in a string and convert it to the corresponding variable type example ' 12.1 ', ' Ten ', ' String '->12.1,10, ' string '
How to determine the type of a value in a string and convert it to the corresponding variable type.
For example, there is a variable $ A = Array (' 12.1 ', ' ' X ', ' string '); to make it into an array (12.1,10, ' string '); What should I do?
I use the Eval function to do the next, there will be warnings, although can be used to suppress, after all, is not a good way to use the regular?
My turn type is used to insert data into the database. What methods does the database have to do this conversion not (my database knowledge sucks)?
You are a master of the fulcrum.
Here's the code I did with the Eval function.
PHP Code
$a = Array ("12.1", "Ten", "Sting"), foreach ($a as $t) { eval ("\ $t = $t;"); Var_dump ($t); Echo '
';}
------Solution--------------------
I am also a beginner, according to just learn a little bit of knowledge, try to make up a piece of code, see is not what you want:
$a =array ("n", "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). '
';
?>
The results of the operation are shown below:
12:string
10.8:string
String:string
12:integer
10.8:double
String:string
――――――――――
------Solution--------------------
The/*** assigns the correct type to the incoming data **/
function format (& $v) {
if (Is_array ($v)) {
$v = array_map (' format ', $v);
}
if (Is_numeric ($v)) $v + = 0;
return $v;
}
$a = Array ("12.1", "Ten", "sting");
Var_dump ($a);
Format ($a);
Var_dump ($a);
Before execution
Array (3) {
[0]=>
String (4) "12.1"
[1]=>
String (2) "10"
[2]=>
String (5) "Sting"
}
After execution
Array (3) {
[0]=>
Float (12.1)
[1]=>
Int (10)
[2]=>
String (5) "Sting"
}