【问题标题】:Php function with ifelse, foreach and in_array带有 ifelse、foreach 和 in_array 的 PHP 函数
【发布时间】:2013-08-01 11:15:31
【问题描述】:

瞄准。多次(在多个地方)需要检查数组键的值,并根据foreach里面的值需要回显货币代码。

有数组(例如),命名为$data_pvn_1_ii_each_invoice_debit

Array ( 
[0] => Array ( [VatCodeCountryCode] => IE [VatCode] =>123456 ) 
[1] => Array ( [VatCodeCountryCode] => GB [VatCode] =>958725 ) 
)

在这里定义变量,其中包括国家的缩写,其中货币为欧元。

$country_codes_with_euro_currency = array( 'AT', 'BE', 'CY', 'DE', 'EE', 'GR', 'ES', 'FI', 'FR', 'IE', 'IT', 'LU', 'MT', 'NL', 'PT', 'SI', 'SK' );

然后多次(在多个地方)需要检查[VatCodeCountryCode]的值并根据国家代码需要回显货币

一开始尝试获取[VatCodeCountryCode]

foreach($data_pvn_1_ii_each_invoice_debit as $i => $result){
$trim_result_vat_country_code = trim($result[VatCodeCountryCode]);
}

然后函数(函数的一部分)

function myTest($trim_result_vat_country_code) {

if ( in_array($trim_result_vat_country_code), $country_codes_with_euro_currency) ) {
return $currency_code = 'EUR'; 
}

elseif ( $trim_result_vat_country_code == 'GB' ) {
return $currency_code = 'GBP';
}   

}

然后需要回显货币代码(也只是部分代码)

<?php foreach($data_pvn_1_ii_each_invoice_debit as $i => $result){?>
<tr><td>
<?php echo myTest($trim_result_vat_country_code); ?>
</td></tr>
<tr><td>content of other td</td></tr>
<?php }?>

第一个问题:代码不适用于( in_array($trim_result_vat_country_code), $country_codes_with_euro_currency) )

第二个问题:echo myTest($trim_result_vat_country_code); 只返回最后一个结果。对于数组键VatCodeCountryCode,有值IEGB。所以需要呼应货币EURGBP。但只回显GBP

【问题讨论】:

    标签: php arrays function foreach


    【解决方案1】:

    第一个问题:

    if( in_array($trim_result_vat_country_code), $country_codes_with_euro_currency))
    

    应该是

    if( in_array($trim_result_vat_country_code, $country_codes_with_euro_currency))
    

    in_array 函数中的第二个参数应该是array

    第二个问题:

    foreach($data_pvn_1_ii_each_invoice_debit as $i => $result){
      $trim_result_vat_country_code = trim($result[VatCodeCountryCode]);
    }
    

    您上面的代码只保存最后一条记录。这就是myTest 函数只返回最后一条记录的原因。

    解决方案:

    <?php foreach($data_pvn_1_ii_each_invoice_debit as $i => $result){?>
    <tr><td>
    <?php echo myTest($result['VatCodeCountryCode']); ?>
    </td></tr>
    <tr><td>content of other td</td></tr>
    <?php }?>
    

    修改你的myTest函数

    function myTest($trim_result_vat_country_code) {
        global $country_codes_with_euro_currency;
        if ( in_array($trim_result_vat_country_code, $country_codes_with_euro_currency) ) {
            return $currency_code = 'EUR';
        } elseif ( $trim_result_vat_country_code == 'GB' ) {
            return $currency_code = 'GBP';
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 2019-06-29
      • 2013-03-01
      • 2016-12-02
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      相关资源
      最近更新 更多