我正在尝试打开包含各种数据类型的输入文件。像这样:
Woof
50
Meow
30
//...
而且我不太清楚该怎么做。我已经搜索了方法,我找到了类似ctype_digit
,is_digit
和is_string
的内容。我测试了它们,但我仍然没有得到预期的结果。
这是我正在使用的代码段:
// Sorts the array by requested data type
function sortArray($anArray, $dataType){
$array_string = array();
$array_int = array();
foreach ($anArray as $element){
if (ctype_digit($element)){
array_push($array_int, $element);
}
elseif (ctype_alpha($element)){
array_push($array_string, $element);
}
}
if ($dataType == "int"){
return $array_int;
}
elseif ($dataType == "String"){
return $array_string;
}
} // end function sortArray($anArray, $dataType)
任何人都可以帮忙指出它为什么不起作用吗?
答案 0 :(得分:0)
你的功能好像很复杂。只需使用array_filter()
过滤掉您不想要的所有其他值,如下所示:
<?php
//As an example to get the data from the file nice and quick
$lines = array_map("trim", file("test.txt", FILE_IGNORE_NEW_LINES));
function filterArrayByType($arr, $type = "int") {
return array_filter($arr, ($type === "int"?"ctype_digit":"ctype_alpha"));
}
$result = filterArrayByType($lines, "string"); //"int"
print_r($result);
?>
输出:
Array ( [0] => Woof [2] => Meow ) //Array ( [1] => 50 [3] => 30 )
答案 1 :(得分:0)
is_string()和is_float()将给出true或false。 (浮点数可以是12.21)
请记住,数字也可以是字符串。这一切都与你如何写它有关。所以is_string必须是is_检查行中的最后一行。
is_string('23') = true
is_string(23) = false
is_string('23.5') = true
is_string(23.5) = false