我正在尝试打开一个包含各种数据类型的输入文件。类似这样的东西:
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)
有人能帮忙指出为什么它不起作用吗?
你的函数似乎有点复杂。只需像这样用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 )
- is_string()-查找变量的类型是否为字符串
- is_float()-查找变量的类型是否为float
- is_int()-查找变量的类型是否为整数
- is_bool()-查找变量是否为布尔值
- is_object()-查找变量是否为对象
- is_array()-查找变量是否为数组
请记住,数字也可以是字符串。这一切都取决于你如何写。所以is_string必须是一行is_检查中的最后一个。
is_string('23') = true
is_string(23) = false
is_string('23.5') = true
is_string(23.5) = false