为什么将值转换为字符串会改变重写数组值时代码的行为?

问题描述 投票:0回答:1

我在尝试更新数组中的值时遇到问题。具体来说,我的这部分代码似乎有问题:

$response["rates"][$key[$i]] = (string) round($response["rates"][$key[$i]], 2);

这是数组的 var_dump

array(11) {
  ["result"]=>
  string(7) "success"
  ["provider"]=>
  string(32) "https://www.exchangerate-api.com"
  ["documentation"]=>
  string(42) "https://www.exchangerate-api.com/docs/free"
  ["terms_of_use"]=>
  string(38) "https://www.exchangerate-api.com/terms"
  ["time_last_update_unix"]=>
  int(1714003352)
  ["time_last_update_utc"]=>
  string(31) "Thu, 25 Apr 2024 00:02:32 +0000"
  ["time_next_update_unix"]=>
  int(1714090382)
  ["time_next_update_utc"]=>
  string(31) "Fri, 26 Apr 2024 00:13:02 +0000"
  ["time_eol_unix"]=>
  int(0)
  ["base_code"]=>
  string(3) "USD"
  ["rates"]=>
  array(162) {
    ["USD"]=>
    float(1)
    ["AED"]=>
    float(3.6699999999999999289457264239899814128875732421875)
    ["AFN"]=>
    float(72.1299999999999954525264911353588104248046875)
    ["ALL"]=>
    float(94.2999999999999971578290569595992565155029296875)
    ["AMD"]=>
    float(391.30000000000001136868377216160297393798828125)
    ["ANG"]=>
    float(1.79000000000000003552713678800500929355621337890625)
    ["AOA"]=>
    float(843.5700000000000500222085975110530853271484375)
    ["ARS"]=>
    float(864.75)
  }
}

但是,当我使用以下行时:

$response["rates"][$key[$i]] = round($response["rates"][$key[$i]], 2);

数值保持不变。我很困惑为什么在这种情况下转换为字符串会产生影响。

我的其余代码按预期运行。它从 URL 获取 JSON 数据并将其转换为数组。

这是带注释的代码:

<?php

$req_url = 'https://open.er-api.com/v6/latest/USD'; // URL for the request
$response_json = file_get_contents($req_url); // Get JSON data from the URL as a string

$response = json_decode($response_json, true); // Convert the string to an array

$key = array_keys($response["rates"]); // Get all keys from the array
/* var_dump of $key
{
  [0]=>
  string(3) "USD"
  [1]=>
  string(3) "AED"
  [2]=>
  string(3) "AFN" and etc.
}
*/

if ('success' === $response["result"]) { // Check if the request was successful

    for ($i = 0; $i < sizeof($response["rates"]); $i++) {
        // Attempt to update values in the array (doesn't seem to work as expected)
        // Do not change any value of array

        $response["rates"][$key[$i]] = round($response["rates"][$key[$i]], 2);
    }

    for ($i = 0; $i < sizeof($response["rates"]); $i++) {
        // Another attempt to update values, casting to string this time
        // Change value of array after cast to string

        $response["rates"][$key[$i]] = (string)round($response["rates"][$key[$i]], 2);
    }

}

任何见解将不胜感激!

我已尝试研究此问题,但尚未找到此行为的任何解决方案或解释。

(数组属性。公共论坛上的类似问题,ChatGPT)

php arrays casting
1个回答
0
投票

对这个问题进行更深入的研究后,即。

检查

https://3v4l.org/
的各种编译变体,并确保这不是数组或记录中的问题。

问题出在

php.ini
文件中,即
precision

的值中

解决方案:

检查

precision
中的
php.ini
设置,它默认为14,当我将其更改为50时,我们得到了想要的结果。

© www.soinside.com 2019 - 2024. All rights reserved.