我真的找一個功能,可以幫助我轉換值像這樣(的var_dump後):PHP的字符串轉換爲正確的類型
字符串(2)「49」整數 或字符串(3)「1.2 「 浮。
this不爲我工作 感謝
這裏是我的代碼: 我只是有一個遞歸函數來檢查我的數組
foreach($arr as $key => $value)
{
if(is_array($value))
{
$this->__set_types($value);
}
if(is_numeric($value))
{
echo getcorrectvariable($value);
$arr[$key] = settype($value, gettype_fromstring($value));
var_dump($arr);
}
}
function gettype_fromstring($string){
// (c) José Moreira - Microdual (www.microdual.com)
return gettype(getcorrectvariable($string));
}
function getcorrectvariable($string){
// (c) José Moreira - Microdual (www.microdual.com)
// With the help of Svisstack (https://stackoverflow.com/users/283564/svisstack)
/* FUNCTION FLOW */
// *1. Remove unused spaces
// *2. Check if it is empty, if yes, return blank string
// *3. Check if it is numeric
// *4. If numeric, this may be a integer or double, must compare this values.
// *5. If string, try parse to bool.
// *6. If not, this is string.
$string=trim($string);
if(empty($string)) return "";
if(!preg_match("/[^0-9.]+/",$string)){
if(preg_match("/[.]+/",$string)){
return (double)$string;
}else{
return (int)$string;
}
}
if($string=="true") return true;
if($string=="false") return false;
return (string)$string;
}
這裏的所有元素是我的陣列中的一個PICE (的var_dump)
array(3) {
[0]=>
array(3) {
[0]=>
array(9) {
["id"]=>
string(3) "106"
["idMessageType"]=>
string(1) "1"
["idClientSender"]=>
string(2) "59"
["idClientRecipient"]=>
string(2) "49"
["message"]=>
string(5) "rwert"
["creationTimeStamp"]=>
string(22) "2014-11-04 10:09:12+05"
["readingTimestamp"]=>
NULL
["status"]=>
string(1) "1"
["isMessageActive"]=>
string(1) "t"
}
[1]=>
array(9) {
["id"]=>
string(3) "105"
["idMessageType"]=>
string(1) "1"
["idClientSender"]=>
string(2) "59"
["idClientRecipient"]=>
string(2) "49"
["message"]=>
string(7) "qwrqewr"
["creationTimeStamp"]=>
string(22) "2014-11-04 10:08:56+05"
["readingTimestamp"]=>
NULL
["status"]=>
string(1) "1"
["isMessageActive"]=>
string(1) "t"
}
["client"]=>
array(4) {
["id"]=>
string(2) "49"
["name"]=>
string(12) "а аАаВаИаЛб"
["surname"]=>
string(14) "ааАбаИаПаОаВ"
["photoName"]=>
string(50) "49.jpg "
}
}
爲什麼它不起作用?什麼是字符串,結果是什麼類型?你可以添加一些代碼嗎? – 2014-11-05 20:43:00
我已更新我的問題 – 2014-11-05 20:49:21
不,但它必須是方式 – 2014-11-05 21:15:21