I have an array , I want to get result by passing currency parameter . E.g $array is the variable containing array.
I want to get by this way $array['EUR']['rate']
How can i get by this way. Please Help
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
)
)
I want to get
foreach ($array as $currency) {
if ($currency['currency'] == 'EUR') {
echo $currency['rate'];
}
}
You may want to format the array differently to be able to access data directly without looping. So you could use currency as key.
You can reformat the array like this:
$newArray = [];
foreach ($array as $currency) {
$newArray[$currency['currency']] = $currency;
}
Then access $newArray['EUR']['rate']
Stick it in a getCurrency function. Then just pass in the one you want and the array:
<?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
See it here https://3v4l.org/DnDQo
Try this function:
function formatArray($array){
$return = [];
foreach($array as $arrayItem){
$return[$arrayItem['currency']] = $arrayItem;
}
return $return;
}
current array
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
)
)
So using this function
print_r(formatArray($array));
arry will convert to this:
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
)
)
then you can try like this:
echo $array['EUR']['rate'];