PHP数组的字符串转换为int

时间:2016-10-03 15:09:38

标签: php arrays

我有一个包含一些字符串值的数组

array(4) { 
[0]=> array(2) { ["x"]=> string(13) "1475269218000" ["y"]=> string(1) "1" } 
[1]=> array(2) { ["x"]=> string(13) "1475269222000" ["y"]=> string(1) "1" } 
[2]=> array(2) { ["x"]=> string(13) "1475269231000" ["y"]=> string(1) "1" } 
[3]=> array(2) { ["x"]=> string(13) "1475269241000" ["y"]=> string(1) "1" } 
}

我需要一个只有int值的输出。所以这就是输出。

[
[1475269218000,1],
[1475269222000,1],
[1475269231000,1]
[1475269241000,1]
]

1 个答案:

答案 0 :(得分:1)

选项1:

$ar = [
    ['x' => '1475269218000', 'y' => '1'],
    ['x' => '1475269222000', 'y' => '1'],
    ['x' => '1475269231000', 'y' => '1'],
    ['x' => '1475269241000', 'y' => '1']
];

foreach($ar AS $key1 => $sub_ars) {
    foreach($sub_ars AS $key2 => $val) {
        $ar[$key1][$key2] = intval($val);
    }
}
var_dump($ar);

选项2:

$ar = [
    ['x' => '1475269218000', 'y' => '1'],
    ['x' => '1475269222000', 'y' => '1'],
    ['x' => '1475269231000', 'y' => '1'],
    ['x' => '1475269241000', 'y' => '1']
];

function intvalRecursive($val)
{
    if(is_array($val)) {
        return array_map('intvalRecursive', $val);
    }
    return intval($val);
}

$ar = array_map('intvalRecursive', $ar);
var_dump($ar);

选项3(剥离键):

$ar = [
    ['x' => '1475269218000', 'y' => '1'],
    ['x' => '1475269222000', 'y' => '1'],
    ['x' => '1475269231000', 'y' => '1'],
    ['x' => '1475269241000', 'y' => '1']
];

foreach($ar AS $key => $val) {
    $ar[$key] = array_values(array_map('intval', $val));
}
var_dump($ar);