Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:将数组的所有数值字段分别转换为ins或浮点_Php_Arrays - Fatal编程技术网

PHP:将数组的所有数值字段分别转换为ins或浮点

PHP:将数组的所有数值字段分别转换为ins或浮点,php,arrays,Php,Arrays,我有一个数组。看起来像这样: [ { "id": "2", "number": "2", "debtor_number": null, "name": "Ziegler", "firstname": "Lisa", "credit": "0.00", }, { "id": "3", "number": "3",

我有一个数组。看起来像这样:

[
    {
        "id": "2",
        "number": "2",
        "debtor_number": null,
        "name": "Ziegler",
        "firstname": "Lisa",            
        "credit": "0.00",
    },
    {
        "id": "3",
        "number": "3",
        "debtor_number": null,
        "name": "Ziegler",
        "firstname": "Lisa",            
        "credit": "51.20",
是否可以将所有数字文件(如
2
51.20
分别转换为整数和浮点值(我的意思是不手动)

我是这样做的:

             foreach ($array as &$val) {
                    foreach ($val as &$value) {
                        if(is_numeric($value)){
                            if(ctype_digit($value))
                                $value= (int)$value;
                            else
                                $value = (float)$value;
                        }
                    }
                }

如果阵列的深度可能不同,并且您希望它适用于所有级别,则可以使用:

array_walk_recursive($arr, function(&$val) {
    if (is_numeric($val)) {
        if (ctype_digit($val)) {
            $val= (int) $val;
        } else {
            $val = (float) $val;
        }
    }
});