所以我一直在问很多基于数组的问题,因为我努力了解PHP的主要数据结构来源。每个第三个元素都应该在它旁边有一个日期
我目前正在建立一个类,吐出艺术家和他们的歌曲列表。每首第三首歌曲旁边都有一个日期。因为这个数组中看出:
$music = array(
'Creed' => array(
'Human Clay' => array(
array(
'title' => 'Are You Ready'
),
array(
'title' => 'What If'
),
array(
'title' => 'Beautiful',
'date' => '2012'
),
array(
'title' => 'Say I'
),
array(
'title' => 'Wrong Way'
),
array(
'title' => 'Faceless Man',
'date' => '2013'
),
array(
'title' => 'Never Die'
),
array(
'title' => 'With Arms Wide pen'
),
array(
'title' => 'Higher',
'date' => '1988'
),
array(
'title' => 'Was Away Those Years'
),
array(
'title' => 'Inside Us All'
),
array(
'title' => 'Track 12',
'date' => '1965'
),
),
),
);
我写什么是以下几点:
class Music{
protected $_music = array();
protected $_html = '';
public function __construct(array $music){
$this->_music = $music;
}
public function get_music(){
$year = '';
$this->_html .= '<d1>';
foreach($this->_music as $artist=>$album){
$this->_html .= '<dt>' . $artist . '</dt>';
foreach($album as $track=>$song){
foreach($song as $songTitle){
if(isset($songTitle['date']) && !empty($songTitle['date'])){
$year = '['.$songTitle['date'].']';
}
$this->_html .= '<dd>' . $songTitle['title'] . $year. '</dd>';
}
}
}
$this->_html .= '</d1>';
}
public function __toString(){
return $this->_html;
}
}
$object = new Music($music);
$object->get_music();
echo $object;
我的问题是,我最终得到的东西回来,看起来像这样:
Creed
Are You Ready
What If
Beautiful[2012]
Say I[2012]
Wrong Way[2012]
Faceless Man[2013]
Never Die[2013]
With Arms Wide pen[2013]
Higher[1988]
Was Away Those Years[1988]
Inside Us All[1988]
Track 12[1965]
由于你可以看到几乎每个歌曲在数组中都有一个日期,但情况并非如此。我的问题是什么交易?我认为在我的循环中,我很清楚地说明这首歌是否有一年,然后将其设置并打印在歌曲标题旁边?
请问有人能指出我正确的方向吗?
是的,这是一个错字,哈哈谢谢。 – TheWebs