0

我显然有问题。我一直在阅读Foreach Loops Manual并且显然在一个循环中我需要来自这样一个数组的所有歌曲:

$music = array(
    'Creed' => array(
        'Human Clay' => array(
            array(
                'title' => 'Are You Ready'
            ),
            array(
                'title' => 'What If'
            ),
            array(
                'title' => 'Beautiful'
            ),
            array(
                'title' => 'Say I'
            ),
            array(
                'title' => 'Wrong Way'
            ),
            array(
                'title' => 'Faceless Man'
            ),
            array(
                'title' => 'Never Die'
            ),
            array(
                'title' => 'With Arms Wide pen'
            ),
            array(
                'title' => 'Higher'
            ),
            array(
                'title' => 'Was Away Those Years'
            ),
            array(
                'title' => 'Inside Us All'
            ),
            array(
                'title' => 'Track 12'
            ),
        ),
    ),
)

到目前为止,我所拥有的是:

foreach($music['Creed']['Human Clay'] as $song){
   var_dump($song);
}

问题是,$song 是一个数组。我必须在一个循环中执行此操作。这可能吗?

4

3 回答 3

5

是的!

foreach($music['Creed']['Human Clay'] as $song){
   echo $song['title'];
}

小提琴: http: //phpfiddle.org/main/code/rek-bcn

于 2012-12-31T17:25:31.327 回答
0
function getSongsList($arr, $album){
 $length = count($arr['Creed'][$album]);
 $result = array();
 for ($i = 0; $i < $length; $i++){
  $result[$i] = $arr['Creed'][$album][$i]['title'];
 }
 return $result;
}

//Usage

print_r(getSongsList($music, 'Human Clay'));
于 2012-12-31T21:25:07.410 回答
0

您也可以使用array_walk_recursive以防例如您不知道每个部分的深度:

$songs = [];    
array_walk_recursive($music, function($v) use (&$songs) {$songs[] = $v;});
print_r($songs);
于 2012-12-31T17:46:06.630 回答