Home > Back-end >  Foreach loop specific subarray values in PHP array?
Foreach loop specific subarray values in PHP array?

Time:07-24

I want to echo all the "label" and "contents" values of the subarray "tabs" (0,1 and 2) within in the following array.

$content=
[
  'musescore' => 'https://musescore.com/user/4534311/scores/8352662',
  'downloads' => [
    0 => 'afoxe2.mscz',
    1 => 'afoxe2.mscz',
  ],
  'tabs' => [
    0 => [
      'label' => 'Misc',
      'content' => '09832209761',
    ],
    1 => [
      'label' => 'Playlist',
      'content' => 'https://youtube.com/playlist?list=PL1qJLXCMC3vUSDduCV7IZJBfEpyXHYx0R',
    ],
    2 => [
      'label' => 'Afoxé',
      'content' => 'More than a rhythm, Afoxé incorporates choreography, song, ritual language and ceremonies deriving from the Brazilian Candomblé religion. Driving it is the Afro-Brazilian Ijexá rhythm, traditionally played with an Afoxé, a large guard shaker covered with a net of beads, three Atabaques, tall conga-like hand drums, and an Agogô, a two pitched bell.',
    ],
  ],
];

This seems like it should work, but it doesn't:

foreach($content as $i){
    foreach($i['tabs'] as $key => $value){
        echo $key.'->'.$value;
    }
}

I am missing something simple. Any help would be appreciated.

CodePudding user response:

You only need a single loop iterating over $content['tabs']:

This probably is what you are looking for:

foreach($content['tabs'] as $key => $tab){
    echo $key . ": " . $tab['label'] . '->' . $tab['content']  ."\n";
}
  •  Tags:  
  • php
  • Related