【发布时间】:2015-08-19 15:19:09
【问题描述】:
我有以下函数,旨在使用来自 url ($id) 的 ID 和在网页上显示信息的 foreach 语句从艺术家那里获取特定歌曲的所有学分。目前它可以很好地显示艺术家姓名,但没有显示 ID。我将如何返回 ID 信息以使其也显示出来?
function getArtistsBySongId($id)
{
$query = "SELECT * FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
LEFT OUTER JOIN `Song` AS s ON s.song_id = c2a.song_id
LEFT OUTER JOIN `Project` AS p ON p.project_id = s.project_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$artists = Array();
$artisttoid = Array();
$songtoid = Array();
while( $row = mysql_fetch_array($res) ) {
$artist = $row[artist_name];
$credit = $row[credit_name];
$songcr = $row[song_id];
if(!array_key_exists($artist, $artists) ) {
$artists[$artist] = Array();
$artisttoid[$artist] = $row[artist_id];
$songtoid[$songcr] = $row[song_id];
}
$artists[$artist][] = $credit;
}
return $artists;
return $songtoid;
return $artisttoid;
}
我在代码中使用了 include,因为我对 PHP 还很陌生,并且发现它更容易理解。
<table border="0" cellspacing="5" cellpadding="5" class="cdinfo" width="100%;">
<tr>
<?php
if (getArtistsBySongId($id) == NULL) {
echo "<th style='font-size: 13px'>Credits:</th>";
echo "<td style='font-size: 13px'>There are currently no artists linked to this song.</td>";
} else {
include 'songs/getsongcredits.php';
}
?>
</tr>
</table>
歌曲/getsongcredits.php
<?php foreach (getArtistsBySongId($id) as $artist => $creditarr) {
$credits = implode( ", ", $creditarr );
echo "<a href='star.php?id={$artisttoid[$artist]}'>{$artist}</a> ({$credits})<br />";
} ?>
【问题讨论】:
-
我会返回一个对象。你也可以使用数组。
-
如果可以的话,你应该stop using
mysql_*functions。它们不再被维护并且是officially deprecated。改为了解 prepared statements,并考虑使用 PDO,it's really not hard。 -
您应该在数组的字符串索引周围加上引号,例如
$row['artist_name']。不要依赖 PHP 自动引用无法识别的常量。
标签: php function foreach return