因此,当我努力了解 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]
正如您所看到的,几乎每首歌曲旁边都有一个日期,而在数组中并非如此。我的问题是什么交易?我想在我的循环中我很清楚地说明这首歌是否有年份,设置它然后在歌曲标题旁边打印它?
有人可以指出我正确的方向吗?