How to return an array and subarray value?

Asked

Viewed 87 times

0

Good afternoon, my question is this::

I own a array of genera. Code below:

$generos = array(
    'filmes' => array(
        1 => 'Ação'
    ), 

    'series' => array(
        1 => 'Artes Marciais'
    ), 

    'animes' => array(
        1 => 'Aventura'
    )
);

I need to return this array showing all the codes inside it, example: ela irá mostrar todos os valores disponíveis dentro de um dos gêneros, vamos supor que você escolheu o gênero: FILMES, é necessário que me retorne todos os valores dentro dessa array, this way above I am not knowing how to return, because it has an array and a sub-array. I can only return the complete values of an array when a array is like this:

$generos = array('filmes' => 'Ação', 'series' => 'Artes Marciais', 'animes' => 'Aventura');
foreach($generos as $key => $value) {
    echo $value.', ';
}

Ai returns to me Ação, Artes Marciais, Aventura,, but when I use subarray as it is in the first code, I cannot make the return, I would like help.

1 answer

1


Make a second foreach like this:

$generos = array(
    'filmes' => array(
        1 => 'Ação'
    ), 

    'series' => array(
        1 => 'Artes Marciais'
    ), 

    'animes' => array(
        1 => 'Aventura'
    )
);

foreach($generos as $key => $value) {
    foreach($value as $_key => $subvalue){
       echo $subvalue.', '; 
    }
}

Giving echo into the key

foreach($generos as $key => $value) {
        foreach($value as $_key => $subvalue){
           echo $_key.', '; 
        }
    }

If you need to know about movies just do so:

foreach($generos['filmes'] as $key => $value) {
        echo $value.', '; 
}


foreach($generos['filmes'] as $key => $value) {
        echo $key.', '; 
}
  • God, you helped me so much, thank you :D

  • It only takes me one more doubt, as I do inside this same code, instead of taking the value, take the position, example: 1 = Action, but I do not want the Ação, I want the number 1, how should I do?

  • the number 1 for example just exchange the echo $value for the echo $key; I put more examples check it out.

  • It is I read, thank you very much helped me too :D

  • Starch ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.