2013-02-04

php大數bigint與json decode的轉換

這問題是在處理facebook介接會遇到的,facebook所傳的json資料有很多使用到bigint,
但是json_decode遇到bigint時會轉成float輸出,雖然可以指定預到大數時自動當成文字,
可是此功能只支援於php 5.4之後的版本,因此不一定都能通用。



我想到的做法如下:

/**
將bigint當文字輸出
*/
function json_big_decode($code , $assoc = true) {
    return PHP_VERSION >= 5.4 // 此版本後才開始支援 JSON_BIGINT_AS_STRING
        ? json_decode( $code, $assoc, 512, JSON_BIGINT_AS_STRING)
        : json_decode(
            preg_replace('/([{|,]\s*"[^"]+"\s*:\s*)(-?[\d]{10,})/', '\\1"\\2"', $code)
            , $assoc
        )
    ;
}
/**
將資料文字中大數轉為bigint輸出
*/
function json_big_encode($data) {
    return preg_replace('/([{|,]\s*"[^"]+"\s*:\s*)"(-?\d{1,20})"/', '\\1\\2', json_encode($data));
}

沒有留言:

張貼留言