16

假设我有一个这样的字符串$thestring = "1,2,3,8,2"

如果explode(',', $thestring)是这样,我会得到一个字符串数组。如何将其分解为整数数组?

4

6 回答 6

40

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)
}

示例键盘

于 2013-02-28T12:14:47.067 回答
12

使用这样的东西:

$data = explode( ',', $thestring );
array_walk( $data, 'intval' );

http://php.net/manual/en/function.array-walk.php

于 2013-02-28T12:11:58.443 回答
1

在大多数情况下,您实际上并不需要(PHP 通常擅长处理强制转换字符串和浮点数/整数),但如果绝对必要,您可以array_walk使用intvalor 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)
}
于 2013-02-28T12:13:27.823 回答
0

因为 $thestring 是一个字符串,所以你会得到一个字符串数组。

只需在爆炸值前面添加 (int) 即可。

或者使用 array_walk 函数:

$arr = explode(',', $thestring);
array_walk($arr, 'intval');
于 2013-02-28T12:12:46.387 回答
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 ) 
于 2013-02-28T12:14:18.480 回答
0
$arr=explode(',', $thestring);
$newstr   = '';
foreach($arr as $key=>$val){
  $newstr .= $val; 
}
于 2013-02-28T12:15:05.003 回答