我需要从平面字符串数组中提取
Title
、Album
和 Artist
的重复值集。
注意
file:
前缀元素代表一组新数据的开始。
样本输入:
$playlistid = [
'MPD 0.23.5',
'file: Blondie/Parallel_Lines/12_Just_Go_Away.flac',
'Last-Modified: 2016-06-05T17:15:07Z',
'Format: 44100:16:2',
'Album: Parallel Lines',
'AlbumArtist: Blondie',
'Artist: Blondie',
'Composer: Debbie Harry',
'Date: 1978',
'Genre: Rock',
'Title: Just Go Away',
'Track: 12',
'Time: 214',
'duration: 213.800',
'Pos: 0',
'Id: 745',
'file: Blondie/Parallel_Lines/13_Once_I_Had_a_Love-aka_The_Disco_Song-1978_version-.flac',
'Last-Modified: 2016-06-05T17:15:01Z',
'Format: 44100:16:2',
'Album: Parallel Lines',
'AlbumArtist: Blondie',
'Artist: Blondie',
'Composer: Chris Stein; Debbie Harry',
'Date: 1978',
'Genre: Rock',
'Title: Once I Had a Love (aka The Disco Song) (1978 version)',
'Track: 13',
'Time: 198',
'duration: 198.000',
'Pos: 1',
'Id: 746',
'file: Blondie/Parallel_Lines/14_Bang_a_Gong-Get_It_On-live-.flac',
'Last-Modified: 2016-06-05T17:15:03Z',
'Format: 44100:16:2',
'Album: Parallel Lines',
'AlbumArtist: Blondie',
'Artist: Blondie',
'Composer: Marc Bolan',
'Date: 1978',
'Genre: Rock',
'Title: Bang a Gong (Get It On) (live)',
'Track: 14',
'Time: 330',
'duration: 330.293',
'Pos: 2',
'Id: 747',
''
];
我有一个 foreach 循环,它在上面的数组中搜索所需的字段,并生成三个具有所需键的数组。
foreach($playlistid as $key => $value) {
if (preg_match('/\bTitle:\s/', $value)) {
$song_title = $playlistid[$key];
}
if (preg_match('/\bArtist:\s/', $value)) {
$song_artist = $playlistid[$key];
}
if (preg_match('/\bAlbum:\s/', $value)) {
$album_title = $playlistid[$key]
}
}
我正在寻找的结果是这样的输出:
Artist, Album, Title
Blondie Parallel Lines Just Go Away
Blondie Parallel Lines Once I Had a Love (aka The Disco Song) (1978 version)
Blondie Parallel Lines Bang a Gong (Get It On) (live)
值得注意的是,例如对于不同的专辑,艺术家和专辑标签也会随着每首新曲目而变化。
file
标签,新建一个引用变量,压入结果数组中Artist
、Album
或 Title
标签,将该值推入引用变量。代码:(演示)
function parse(array $lines): array
{
$result = [];
foreach ($lines as $line) {
$split = explode(': ', $line, 2);
switch ($split[0]) {
case 'file':
unset($ref);
$ref = [null, null, null];
$result[] = &$ref;
break;
case 'Artist':
$ref[0] = $split[1];
break;
case 'Album':
$ref[1] = $split[1];
break;
case 'Title':
$ref[2] = $split[1];
break;
}
}
return $result;
}
现在数据已经被解析并且多维数组已经被填充,将您的数据呈现给最终用户将是一件微不足道的事情。