JSON_NUMERIC_CHECK and phone numbers

前端 未结 7 1126
执念已碎
执念已碎 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:11

    Instead of typecasting it to a string do something like this:

    $output = array(
        'is_bool' => 1,
        'total_amount' => '431.65',
        'phone_number' => '"0272561313"' // add quotations
    );
    
    echo '
    ';
    echo json_encode($output,JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    

    It'l keep the trailing zero:

    {
        "is_bool": 1,
        "total_amount": 431.65,
        "phone_number": "\"0272561313\""
    }
    

    Decode:

    $test = json_encode($output,JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    $test = json_decode($test, true);
    print_r($test);
    

    Output:

    Array
    (
        [is_bool] => 1
        [total_amount] => 431.65
        [phone_number] => "0272561313"
    )
    

提交回复
热议问题