简体   繁体   中英

Can I get the effect of JSON_NUMERIC_CHECK without JSON?

Can i get the effect of JSON_NUMERIC_CHECK without JSON?

ie Recrusive replacement of numeric strings to ints or floats.

Example with 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?

You can loop over your string s and cast any numeric value to int or float using the following code:

/**
 * 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 :)

More efficient way

/**
 * 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.

$data = explode(',', 'abc,7,3.14');
$re = array_map(function(&$a) {
   return ctype_digit($a) ? intval($a) : $a;
}, $data);
var_dump($re);

https://eval.in/715641

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM