php 字符串到整数数组php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8963910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String to array of Integers php
提问by snake plissken
I wan to convert a string for example 1,2,3,4,5,6 to an array of integers in php? I find functions that only have access to the first character of the string for example 1. How can I conert the whole string to array?
我想将字符串(例如 1、2、3、4、5、6)转换为 php 中的整数数组?我发现只能访问字符串的第一个字符的函数,例如 1。如何将整个字符串转换为数组?
function read_id_txt()
{
$handle_file = fopen("temporalfile.txt", 'r');
$i=0;
while ($array_var[$i] = fgets($handle_file, 4096)) {
echo "<br>";
print_r($array_var[i]);
$i++;
}
fclose($handle_file);
$temp=explode(" ", $array_var[0]);
return $temp;
}
回答by Josh
Use PHP's explode.
使用 PHP 的爆炸。
$str = "1,2,3,4,5,6";
$arr = explode("," $str); // array( '1', '2', '3', '4', '5', '6' );
foreach ($arr AS $index => $value)
$arr[$index] = (int)$value;
// casts each value to integer type -- array( 1, 2, 3, 4, 5, 6 );
As suggested by Tim Cooper, using array_walkis simpler than the above loop:
正如Tim Cooper所建议的,使用array_walk比上面的循环更简单:
array_walk($arr, 'intval');
回答by user2001487
return array_map('intval', explode(",", '1,2,3,4,5,6,7,8,9'));
回答by Oyeme
explode(",",'1,2,3,4,5,6,7,8,9');
回答by CommandZ
The above answers could potentially return non-numeric values
上述答案可能会返回非数字值
array_walk & array_map with intval
array_walk 和 array_map 与 intval
Both return arrays that are tainted with non-numeric values.
两者都返回受非数字值污染的数组。
$string = ',g,6,4,3,f,32,a,';
$array = explode(',', $string);
array_walk($array, 'intval');
$arrayMap = array_map('intval', $array);
var_dump($array);
var_dump($arrayMap);
/*
array(9) {
[0]=>
string(0) ""
[1]=>
string(1) "g"
[2]=>
string(1) "6"
[3]=>
string(1) "4"
[4]=>
string(1) "3"
[5]=>
string(1) "f"
[6]=>
string(2) "32"
[7]=>
string(1) "a"
[8]=>
string(0) ""
}
*/
array_filter to only return numeric values
array_filter 只返回数值
$string = ',g,6,4,3,f,32,a,';
$array = explode(',', $string);
$numericOnlyArray = array_filter($array,'is_numeric');
var_dump($numericOnlyArray);
/*
result:
array(4) {
[2]=>
string(1) "6"
[3]=>
string(1) "4"
[4]=>
string(1) "3"
[6]=>
string(2) "32"
}
*/
To get only integers
只获取整数
$string = ',g,6,4,3,f,32,a,';
$array = explode(',', $string);
$result = array_map('intval', array_filter($array, 'is_numeric'));
var_dump($result);
/*
result:
array(4) {
[2]=>
int(6)
[3]=>
int(4)
[4]=>
int(3)
[6]=>
int(32)
}
}
*/