代码之家  ›  专栏  ›  技术社区  ›  cusspvz

如何获取字符串中值的实际类型?

  •  1
  • cusspvz  · 技术社区  · 16 年前

    我需要一个像“gettype”这样的函数来完成上面的结果,但我不能全部完成:s

    gettypefromstring("1.234"); //returns (doble)1,234;
    gettypefromstring("1234"); //returns (int)1234;
    gettypefromstring("a"); //returns (char)a;
    gettypefromstring("true"); //returns (bool)true;
    gettypefromstring("khtdf"); //returns (string)"khtdf";
    

    感谢所有人:)

    2 回复  |  直到 16 年前
        1
  •  7
  •   cusspvz    16 年前

    1+代表Svisstack!;)

    function gettype_fromstring($string){
        //  (c) José Moreira - Microdual (www.microdual.com)
        return gettype(getcorrectvariable($string));
    }
    function getcorrectvariable($string){
        //  (c) José Moreira - Microdual (www.microdual.com)
        //      With the help of Svisstack (http://stackoverflow.com/users/283564/svisstack)
    
        /* FUNCTION FLOW */
        // *1. Remove unused spaces
        // *2. Check if it is empty, if yes, return blank string
        // *3. Check if it is numeric
        // *4. If numeric, this may be a integer or double, must compare this values.
        // *5. If string, try parse to bool.
        // *6. If not, this is string.
    
        $string=trim($string);
        if(empty($string)) return "";
        if(!preg_match("/[^0-9.]+/",$string)){
            if(preg_match("/[.]+/",$string)){
                return (double)$string;
            }else{
                return (int)$string;
            }
        }
        if($string=="true") return true;
        if($string=="false") return false;
        return (string)$string;
    }
    

    我用这个函数来判断X是不是Y的倍数。

    $number=6;
    $multipleof=2;
    if(gettype($number/$multipleof)=="integer") echo "The number ".$number." is multiple of ".$multipleoff.".";
    

    但是我工作的框架总是将输入变量作为字符串返回。

        2
  •  5
  •   Svisstack    16 年前

    必须尝试按指定顺序转换:

    1. 支票是双倍的
    2. 否则,如果长度==1,则为char。
    3. 如果不是,这是字符串。
    4. 如果是字符串,请尝试解析为bool。

    不能使用gettype,因为可能会在字符串中写入十进制的字符串类型。

        3
  •  1
  •   agm1984    6 年前

    以下是这一已有9年历史的函数的更新版本:

    /**
     * Converts a form input request field's type to its proper type after values are received stringified.
     *
     * Function flow:
     *      1. Check if it is an array, if yes, return array
     *      2. Remove unused spaces
     *      3. Check if it is '0', if yes, return 0
     *      4. Check if it is empty, if yes, return blank string
     *      5. Check if it is 'null', if yes, return null
     *      6. Check if it is 'undefined', if yes, return null
     *      7. Check if it is '1', if yes, return 1
     *      8. Check if it is numeric
     *      9. If numeric, this may be a integer or double, must compare this values
     *      10. If string, try parse to bool
     *      11. If not, this is string
     *
     * (c) José Moreira - Microdual (www.microdual.com)
     * With the help of Svisstack (http://stackoverflow.com/users/283564/svisstack)
     *
     * Found at: https://stackoverflow.com/questions/2690654/how-to-get-the-real-type-of-a-value-inside-string
     *
     * @param  string $string
     * @return mixed
     */
    
    function typeCorrected($string) {
        if (gettype($string) === 'array') {
            return (array)$string;
        }
    
        $string = trim($string);
    
        if ($string === '0') { // we must check this before empty because zero is empty
            return 0;
        }
    
        if (empty($string)) {
            return '';
        }
    
        if ($string === 'null') {
            return null;
        }
    
        if ($string === 'undefined') {
            return null;
        }
    
        if ($string === '1') {
            return 1;
        }
    
        if (!preg_match('/[^0-9.]+/', $string)) {
            if(preg_match('/[.]+/', $string)) {
                return (double)$string;
            }else{
                return (int)$string;
            }
        }
    
        if ($string == 'true') {
            return true;
        }
    
        if ($string == 'false') {
            return false;
        }
    
        return (string)$string;
    }
    

    FormData.append() 回到正确的PHP类型:

    public function handle($request, Closure $next)
    {
        $input = $request->all();
    
        foreach($input as $key => $value) {
            $input[$key] = $this->typeCorrected($value);
        }
    
        $request->replace($input);
    
        return $next($request);
    }
    
    1. 要创建它,请键入CLI php artisan make:middleware TransformPayloadTypes

    2. 然后贴在上面 handle 功能。

    3. 别忘了把它贴在墙上 typeCorrected private function 在你的中间件类,但我不声称是一个超级专家。

    你可以想象 $request->all() 类型已更正 函数执行此操作。我已经在一个应用程序中运行了几个星期了,所以边缘案例可以保留下来,但实际上,它是按预期工作的。

    // note: `route()` is from Tightenco Ziggy composer package
    const post = await axios.post(route('admin.examples.create', {
        ...this.example,
        category: undefined,
        category_id: this.example.category.id,
    }));
    

    然后,在你的Laravel控制器中,你可以 \Log::debug($request->all()); 看到这样的东西:

    [2020-10-12 17:52:43] local.DEBUG: array (
      'status' => 1,
      'slug' => 'asdf',
      'name' => 'asdf',
      'category_id' => 2,
    ) 
    

    'status' => 1, 而不是 'status' => '1',

    所有这些都允许您通过Axios提交JSON有效负载,并在实际有效负载类型发生变化时在FormRequest类和控制器中接收非嵌套值。我发现其他的解决方案太复杂了。上述解决方案允许您轻松地从纯JavaScript提交平面JSON有效负载(到目前为止,哈哈)。

    推荐文章