PHP中已知货币值,如何遍历数组内对应的计划数据?
如何遍历指定货币对应的plans数据?
嘿,你的代码里有两个关键小问题,导致没法正确拿到mxn对应的plans数据:
- 首先,foreach循环里你用了
$currency作为键名变量,这会直接覆盖你之前定义的$currency = 'mxn'变量,后续判断就失效了; - 其次,if判断里你用的是赋值运算符
=,而不是比较运算符==(或者更严谨的严格比较===),这会把'mxn'直接赋值给$info['currency'],导致这个判断永远为真,不符合你的预期。
下面给你两种可行的实现方法:
方法一:修正原有遍历逻辑
直接调整你的代码,解决上面两个问题即可:
$targetCurrency = 'mxn'; // 换个变量名避免冲突 $currencies = array( array( 'currency' => 'mxn', 'sign' => '$', 'plans' => array( 'tiny' => 429, 'small' => 1319, 'medium' => 3399, 'big' => 6669 ) ), array( 'currency' => 'usd', 'sign' => '$', 'plans' => array( 'tiny' => 29, 'small' => 319, 'medium' => 399, 'big' => 669 ) ) ); foreach($currencies as $info) { // 用严格比较判断当前货币是否是目标货币 if($info['currency'] === $targetCurrency) { // 遍历plans数据 foreach($info['plans'] as $planType => $price) { echo "套餐类型:*{$planType}*,价格:{$info['sign']}{$price}\n"; } break; // 找到目标后直接退出循环,提升效率 } }
方法二:先重组数组,后续更高效访问
如果需要多次根据货币代码获取对应数据,建议先把数组重组为以货币代码为键的结构,这样后续不用每次都遍历整个数组:
$targetCurrency = 'mxn'; $currencies = array( // 原数组内容不变 array( 'currency' => 'mxn', 'sign' => '$', 'plans' => array( 'tiny' => 429, 'small' => 1319, 'medium' => 3399, 'big' => 6669 ) ), array( 'currency' => 'usd', 'sign' => '$', 'plans' => array( 'tiny' => 29, 'small' => 319, 'medium' => 399, 'big' => 669 ) ) ); // 重组数组,让货币代码成为外层数组的键 $indexedCurrencies = array_column($currencies, null, 'currency'); // 直接通过货币键获取plans并遍历 if(isset($indexedCurrencies[$targetCurrency]['plans'])) { foreach($indexedCurrencies[$targetCurrency]['plans'] as $planType => $price) { echo "套餐类型:*{$planType}*,价格:{$indexedCurrencies[$targetCurrency]['sign']}{$price}\n"; } }
这种方法的优势是预处理一次后,后续可以直接通过$indexedCurrencies['mxn']或者$indexedCurrencies['usd']快速获取对应的数据,不用每次都循环遍历整个数组,适合需要多次查询的场景。
内容的提问来源于stack exchange,提问作者user4440254
相关产品推荐
相关产品推荐

