[英]Can I get the effect of JSON_NUMERIC_CHECK without JSON?
Can i get the effect of JSON_NUMERIC_CHECK without JSON? 我可以在没有JSON的情况下获得JSON_NUMERIC_CHECK的效果吗?
ie Recrusive replacement of numeric strings to ints or floats. 将数字字符串递归替换为整数或浮点数。
Example with JSON_NUMERIC_CHECK: JSON_NUMERIC_CHECK的示例:
<?php
// some input from somewhre
$data = explode(',', 'abc,7,3.14');
echo "Before:"; var_dump($data);
$data = json_decode(json_encode($data, JSON_NUMERIC_CHECK), TRUE);
echo "After:"; var_dump($data);
But I geuss converting to json and back is slow, is there some other way to get the same result? 但是我geuss转换为json并返回的速度很慢,是否还有其他方法可以获得相同的结果?
You can loop over your string
s and cast any numeric value to int
or float
using the following code: 您可以使用以下代码遍历
string
s并将任何数值强制转换为int
或float
:
/**
* Normalize an object, array or string by casting all
* numeric strings it contains to numeric values.
*
* @param array|object|string $data
* @return mixed
*/
function normalize($data) {
if (is_array($data))
return array_map('normalize', $data);
if (is_object($data))
return (object) normalize(get_object_vars($data));
return is_numeric($data) ? $data + 0 : $data;
}
$data = "15,2.35,foo";
$data = normalize(explode(',', $data));
// => [15, 2.35, 'foo']
Hope this helps :) 希望这可以帮助 :)
/**
* Normalize an string or object by casting all
* numeric strings it contains to numeric values.
* Note that it changes the variable directly
* instead of returning a copy.
*
* @param object|string $data
* @return void
*/
function normalizeItem(&$data) {
if (is_object($data)) {
$data = get_object_vars($data);
normalize($data);
$data = (object) $data;
} else {
$data = is_numeric($data) ? $data + 0 : $data;
}
}
/**
* Applies normalizeItem to an array recursively.
*
* @param array &$list
* @return bool
*/
function normalize(&$list) {
return array_walk_recursive($list, 'normalizeItem');
}
You can use array_map()
with a callback. 您可以将
array_map()
与回调一起使用。
$data = explode(',', 'abc,7,3.14');
$re = array_map(function(&$a) {
return ctype_digit($a) ? intval($a) : $a;
}, $data);
var_dump($re);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.