traversing multidimensional associative array in PHP

2

I have a multidimensional associative array and I can not find the way to go through it, being each of the values accessible:

$paises = ['espanya' => $espanya, 'usa' => "$", 'brasil' => "R$", 'canada' => "C$", 'colombia' => "COP", 'hongkong' => "HK$", 'hungria' => "HUF", 'rusia' => "R$", 'singapur' => "S$", 'sudafrica' => "ZAR", 'mexico' => "MXN", 'argentina' => "ARS"];

$espanya = ['€' => 'desc_ES'];

foreach ($paises as $pais => $moneda) {

   //código

}

For example, for the case of the first value of the array espanya I want to access espanya , and desc_ES . Is that possible?

    
asked by JetLagFox 13.04.2017 в 13:33
source

1 answer

3

To begin with, I understand that the definition is the other way around: first define $espanya and then $paises . Otherwise, the value 'espanya' => $espanya will not be converted correctly.

$espanya = ['€' => 'desc_ES'];

$paises = ['espanya' => $espanya, 'usa' => "$", 'brasil' => "R$", 'canada' => "C$", 'colombia' => "COP", 'hongkong' => "HK$", 'hungria' => "HUF", 'rusia' => "R$", 'singapur' => "S$", 'sudafrica' => "ZAR", 'mexico' => "MXN", 'argentina' => "ARS"];

That said, if you want to circulate on a multidimensional array, you must use a loop for each level: one for the countries and another for the content of each of the values. So, I would do:

foreach ($paises as $nombre => $valor) {
   foreach ($valor as $moneda => $desc) {
       print "el pais es $nombre, la moneda $moneda y descr $desc.<br />\n";
   }
}

That will give you something like:

el pais es espanya, la moneda € y descr desc_ES.<br />
    
answered by 13.04.2017 / 13:54
source