0

I have an array of currency codes and their associated countries that looks like this:

$currency_list = array(
  "cad" => array("Canada"),
  "eur" => array("Austria", "Belgium", "Estonia"),
  "aed" => array("United Arab Emirates", "Dubai")
);

I am outputting them like this:

foreach (array_keys($currency_list) as $key) {
  foreach($currency_list[$key] as $value) {
  echo $key." ".$value;
  }
}

Which gives me:

"cad Canada", "eur Austria", "eur Belgium", "eur Estonia", "aed United Arab Emirates"

How can I sort my $currency_list array so that when I loop through it I get the results in alphabetical order of the country like this:

"eur Austria", "eur Belgium", "cad Canada", "eur Estonia", "aed United Arab Emirates"

2

2 Answers 2

2
$sorted = array();
foreach ($currency_list as $currency => $countries) {
    foreach ($countries as $country) {
        $sorted[$country] = $currency;
    }
}

ksort($sorted);

print_r($sorted);  // do your loop here
Sign up to request clarification or add additional context in comments.

Comments

0

Try this..

$currency_list = array(
  "cad" => array("Canada"),
  "eur" => array("Austria", "Belgium", "Estonia"),
  "aed" => array("United Arab Emirates", "Dubai")
);
foreach ($currency_list as $key => $value) {
    foreach ($value as $value1) {
        $newarray[$value1] = $key;
    }
}

ksort($newarray);
foreach($newarray as $key => $value)
{
echo $value." ".$key;
}

Result:eur Austriaeur Belgiumcad Canadaaed Dubaieur Estoniaaed United Arab Emirates

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.