0

我一直在尝试替换数组中的值,当我打印它时,我将把这个数组命名为 $currencies。

Array
(
[0] => Array
    (
        [currencylabel] => USA, Dollars
        [currencycode] => USD
        [currencysymbol] => $
        [curid] => 1
        [curname] => curname1
        [check_value] => 
        [curvalue] => 0
        [conversionrate] => 1
        [is_basecurrency] => 1
    )

[1] => Array
    (
        [currencylabel] => India, Rupees
        [currencycode] => INR
        [currencysymbol] => ₨
        [curid] => 2
        [curname] => curname2
        [check_value] => 
        [curvalue] => 0
        [conversionrate] => 50
        [is_basecurrency] => 
    )

[2] => Array
    (
        [currencylabel] => Zimbabwe Dollars
        [currencycode] => ZWD
        [currencysymbol] => Z$
        [curid] => 3
        [curname] => curname3
        [check_value] => 
        [curvalue] => 0
        [conversionrate] => 22
        [is_basecurrency] => 
    )

)

在这里,我有一个 $conversionRate,我需要将数组 $currencies [0] -> Array -> [conversionrate] 中存在的值除以该值并替换为数组中的相同位置。以及 [1] -> Array -> [conversionrate] 等的相同操作..我目前的方法如下

$conversionRate = 50;
    foreach ($currencies as $key => $val) {
        $key['conversionrate'] = $key['conversionrate'] / $conversionRate;
        if($key['conversionrate'] == 1) {
            $key['is_basecurrency'] = 1;
        }  else {
            $key['is_basecurrency'] = '';
        }
    }
    print_r($key);
    die;

目前这不起作用请帮助

4

3 回答 3

1

你的循环全错了,没有$key['conversionrate'],它是$val['conversionrate']。实际上 $key 变量似乎没有原因,您可以使用循环遍历数组

foreach ($currencies as &$val)

此外,您可能想要 print_r($currencies),而不是 $key

于 2013-05-14T07:55:07.023 回答
1

不要将带有 == 的浮点数与 1 进行比较,它可能由于舍入错误而无法工作。

您混淆了键和值,您需要使用 &$val 才能更改数组。

$conversionRate = 4;
foreach ($currencies as $key => &$val) {
    if($val['conversionrate'] == $conversionRate) {
        $val['is_basecurrency'] = 1;
    }  else {
        $val['is_basecurrency'] = '';
    }
    $val['conversionrate'] = $val['conversionrate'] / $conversionRate;
}
unset($val);
print_r($currencies);
die;
于 2013-05-14T07:55:29.130 回答
0

$key 是数组的索引标识符,$val 包含数组值

所以像这样使用

$conversionRate = 4;
    foreach ($currencies as $key => $val) {
        $val['conversionrate'] = $val['conversionrate'] / $conversionRate;
        if($val['conversionrate'] == 1) {
            $val['is_basecurrency'] = 1;
        }  else {
            $val['is_basecurrency'] = '';
        }
    }
    print_r($val);
    die;
于 2013-05-14T07:54:37.173 回答