JSON_NUMERIC_CHECK and phone numbers

前端 未结 7 1147
执念已碎
执念已碎 2021-01-11 18:45

Our PHP API outputs results using json_encode with JSON_NUMERIC_CHECK enabled, which is important for financial figures, binary values etc.. but we have recently introduced

7条回答
  •  不知归路
    2021-01-11 19:24

    Had the same issue with phone numbers, this walks over an array (no objects!) to cast only numeric values not starting with 0 or + to an int or float.

            array_walk_recursive($json, function (&$value, $key)
            {
                if(is_string($value) && is_numeric($value))
                {
                    // check if value doesn't starts with 0 or +
                    if(!preg_match('/^(\+|0)/', $value))
                    {
                        // cast $value to int or float
                        $value   += 0;
                    }
                }
            });
    
            return json_encode($json);
    

提交回复
热议问题