说我有一个像$thestring = "1,2,3,8,2"
这样的字符串。
如果我explode(',', $thestring)
,我会得到一个字符串数组。我如何将它分解为整数数组?
答案 0 :(得分:26)
array_map
也可以使用:
$s = "1,2,3,8,2";
$ints = array_map('intval', explode(',', $s ));
var_dump( $ints );
输出:
array(5) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
[3]=> int(8)
[4]=> int(2)
}
示例codepad。
答案 1 :(得分:12)
使用类似的东西:
$data = explode( ',', $thestring );
array_walk( $data, 'intval' );
答案 2 :(得分:0)
由于$ thestring是一个字符串,因此你将获得一个字符串数组。
只需在爆炸值前添加(int)。
或者使用array_walk函数:
$arr = explode(',', $thestring);
array_walk($arr, 'intval');
答案 3 :(得分:0)
在大多数情况下你不应该真的需要(PHP通常适用于处理强制转换字符串和浮点数/整数),但如果绝对必要,你可array_walk
使用intval
或floatval
:
$arr = explode(',','1,2,3');
// use floatval if you think you are going to have decimals
array_walk($arr,'intval');
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
如果您需要更详细的内容,还可以查看settype
:
$arr = explode(",","1,2,3");
function fn(&$a){settype($a,"int");}
array_walk($f,"fn");
print_r($f);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
如果您尝试动态投射,那可能会特别有用:
class Converter {
public $type = 'int';
public function cast(&$val){ settype($val, $this->type); }
}
$c = new Converter();
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
)
// now using a bool
$c->type = 'bool';
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
var_dump($arr); // using var_dump because the output is clearer.
array(4) {
[0]=>
bool(true)
[1]=>
bool(true)
[2]=>
bool(true)
[3]=>
bool(false)
}
答案 4 :(得分:0)
$thestring = "1,2,3,8,a,b,2";
$newArray = array();
$theArray = explode(",", $thestring);
print_r($theArray);
foreach ($theArray as $theData) {
if (is_numeric($theData)) {
$newArray[] = $theData;
}
}
print_r($newArray);
//输出
原始数组
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => a [5] => b [6] => 2 )
仅限数字数组
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => 2 )
答案 5 :(得分:0)
$arr=explode(',', $thestring);
$newstr = '';
foreach($arr as $key=>$val){
$newstr .= $val;
}