Convert Numeric Strings In Multi-dimensional Array To Int
Solution 1:
You can use intval
, like the other answers suggested, in conjunction with array_walk_recursive
:
array_walk_recursive($array, function(&$item) {
if (is_numeric($item)) {
$item = intval($item);
}
});
Solution 2:
You can implement a recursive function as follows, which will take an array of any size and dimension.
functionconvertArray(myArray){
convertedArray=array();
foreach(myArray as key=>value){
if(is_array(value)){
convertedArray[key] = convertArray(value);
}else{
temp = intval(value);
if(temp==0){
convertedArray[key] = value;
}else{
convertedArray[key] = temp;
}
}
}
return convertedArray;
}
Solution 3:
Later I have to use this array in json_encode() function and in my javascript process numeric values must be integer-type.
Have you checked the JSON Predefined Constants:
$result = json_encode($array, JSON_NUMERIC_CHECK);
JSON_NUMERIC_CHECK (int)
Encodes numeric strings as numbers. Available as of PHP 5.3.3.
Solution 4:
$variable = array(3) {
[0]=> array(2) {
[0]=> string(3) "ABC"
[1]=> string(3) "744" }
[1]=> array(2) {
[0]=> string(3) "DEF"
[1]=> string(2) "86" }
[2]=> array(2) {
[0]=> string(3) "GHI"
[1]=> string(1) "2" }
}
foreach($variableas$key=>$arrayStrings)
foreach($arrayStringsas$innerKey=>$string)
if(is_numeric($string))
$variable[$key][$innerKey] = intval($string);
Solution 5:
just use intval(string)
;
ref: http://php.net/manual/en/function.intval.php
EDIT:
If you will convert the whole array it wont work. Then you have to test the non-int values so it wont be converted.
inval($value)
will return 0 for non-int value then you have to test if the value was 0 or just non-int value.
If you always have the int value as a second index in array then just use intval($value)
;
foreach ($aas &$ar) {
$ar[1] = intval($ar[1]);
}
Post a Comment for "Convert Numeric Strings In Multi-dimensional Array To Int"