2

Given an array, how do I convert array starting at key [1] from type string to type int?

Array
(
  [0] => "id"
  [1] => "6086220176"
  [2] => "6542925762"
  [3] => "6623113406"
  [4] => "6702782948"
)

I've checked out related question how to convert array values from string to int? already, but I would like to skip the first key "id" int he conversion, and not all keys in array!

4

8 回答 8

4
array_walk($array, function (&$value) {
    if (ctype_digit($value)) {
        $value = (int) $value;
    }
});
var_export($array);

输出:

array (
  0 => 'id',
  1 => 6086220176,
  2 => 6542925762,
  3 => 6623113406,
  4 => 6702782948,
)
于 2013-11-08T16:55:58.213 回答
3
$array = array($array[0]) + array_map('intval', $array);

(如果你想避免 foreach 循环)

于 2013-11-08T16:59:56.177 回答
3
$arr = array_merge(array($arr[0]),array_map('intval', array_slice($arr, 1)));

输出:

array(5) {
  [0]=>
  string(2) "id"
  [1]=>
  int(2147483647)
  [2]=>
  int(2147483647)
  [3]=>
  int(2147483647)
  [4]=>
  int(2147483647)
}

演示。

于 2013-11-08T17:11:25.127 回答
0

如果你所有的价值观都是 int :

<?php
$arr = array(
  [0] => "id"
  [1] => "6086220176"
  [2] => "6542925762"
  [3] => "6623113406"
  [4] => "6702782948"
);

$arr = array_map(function($var) {
    // Your 'id' is not an int and will not be converted.
    return is_numeric($var) ? (int)$var : $var;
}, $arr);
于 2013-11-08T16:56:53.890 回答
0
foreach($array as $k => $v){
  if($k == 0) continue;
  $array[$k] = is_int($v) ? intval($v) : $v; // if it's not convertible to int it keeps the value
}

或者如果您有非数字索引

$skipped = false;
foreach($array as $k => $v){
  if($skipped === false){
    $skipped = true;
    continue;
  }
  $array[$k] = is_int($v) ? intval($v) : $v;
}
于 2013-11-08T16:58:36.250 回答
0

这样做并不聪明,但这可能有效:

$narray = array();
foreach($array as $k => $v){
   $narray[$k+1] = $v;
}
$array = $narray;

$array是您要从 1 开始的数组。

于 2013-11-08T16:53:29.463 回答
0

php 是松散类型的,您不需要键入强制转换它。它会为你做的。但是如果你想明确地这样做,你可以这样做:

$c = count($array)-1;
for ($n=1;$n<$c;$n++) {
  $array[$n] = (int) $array[$n];
}
于 2013-11-08T16:54:41.180 回答
0
foreach($array as $key => $val){
    if($key !== 0){
        $array[$key] = (int) $val;
    }
}

或者

foreach($array as $key => $val){
    if(is_numeric($val)){
        $array[$key] = (int) $val;
    }
}
于 2013-11-08T16:55:25.257 回答