我有一个数组,我想通过传递 currency 参数来获得结果。 例如$ array是包含数组的变量。
我想通过这种方式获得 $ array ['EUR'] ['rate']
如何通过这种方式获得。请帮助
Array
(
[0] => Array
(
[id] => 1
[name] => Andorra
[code] => AD
[currency] => EUR
[phone] => +376
[rate] => 5727.21
)
[1] => Array
(
[id] => 2
[name] => United Arab Emirates
[code] => AE
[currency] => AED
[phone] => +971
[rate] => 24341.9
)
)
我想得到
答案 0 :(得分:1)
foreach ($array as $currency) {
if ($currency['currency'] == 'EUR') {
echo $currency['rate'];
}
}
您可能希望对数组进行格式化,以便能够直接访问数据而不会循环。因此,您可以使用货币作为密钥。
您可以像这样重新格式化数组:
$newArray = [];
foreach ($array as $currency) {
$newArray[$currency['currency']] = $currency;
}
然后访问$newArray['EUR']['rate']
答案 1 :(得分:0)
将其粘贴在getCurrency函数中。然后只需传递您想要的一个和数组:
<?php
$x = [
[
'id' => 1,
'name' => 'Andorra',
'code' => 'AD',
'currency' => 'EUR',
'phone' => '+376',
'rate' => '5727.21',
],
[
'id' => 2,
'name' => 'United Arab Emirates',
'code' => 'AE',
'currency' => 'AED',
'phone' => '+971',
'rate' => '24341.9',
]
];
function getCurrency($code, $currenciesArray)
{
foreach ($currenciesArray as $row) {
if ($row['currency'] == $code) {
return $row;
}
}
return false;
}
$currency = getCurrency('EUR', $x);
echo $currency['rate']; // outputs 5727.21
答案 2 :(得分:0)
尝试此功能:
function formatArray($array){
$return = [];
foreach($array as $arrayItem){
$return[$arrayItem['currency']] = $arrayItem;
}
return $return;
}
当前数组
Array
(
[0] => Array
(
[id] => 1
[name] => Andorra
[code] => AD
[currency] => EUR
[phone] => +376
[rate] => 5727.21
)
[1] => Array
(
[id] => 2
[name] => United Arab Emirates
[code] => AE
[currency] => AED
[phone] => +971
[rate] => 24341.9
)
)
因此使用此功能
print_r(formatArray($array));
arry将转换为此:
Array
(
[EUR] => Array
(
[id] => 1
[name] => Andorra
[code] => AD
[currency] => EUR
[phone] => +376
[rate] => 5727.21
)
[AED] => Array
(
[id] => 2
[name] => United Arab Emirates
[code] => AE
[currency] => AED
[phone] => +971
[rate] => 24341.9
)
)
然后您可以尝试这样:
echo $array['EUR']['rate'];