给定一个数组,如何将从key [1]开始的数组从类型字符串转换为int?
类型Array
(
[0] => "id"
[1] => "6086220176"
[2] => "6542925762"
[3] => "6623113406"
[4] => "6702782948"
)
我已经检查了相关问题how to convert array values from string to int?,但我想跳过转换中的第一个键“id”,而不是数组中的所有键!
答案 0 :(得分: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,
)
答案 1 :(得分: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)
}
答案 2 :(得分:2)
$array = array($array[0]) + array_map('intval', $array);
(如果你想避免foreach循环)
答案 3 :(得分:0)
这样做并不聪明,但这可能有效:
$narray = array();
foreach($array as $k => $v){
$narray[$k+1] = $v;
}
$array = $narray;
$array
是您想要从1开始的数组。
答案 4 :(得分:0)
php是松散类型的,你不需要输入它。它会为你做。但是如果你想明确地这样做,你可以这样做:
$c = count($array)-1;
for ($n=1;$n<$c;$n++) {
$array[$n] = (int) $array[$n];
}
答案 5 :(得分: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;
}
}
答案 6 :(得分: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);
答案 7 :(得分: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;
}