如何在php函数中返回多个结果

时间:2015-06-04 20:30:22

标签: php function foreach return

我有以下功能,旨在使用网址($ 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 />";
} ?>

2 个答案:

答案 0 :(得分:4)

对象或数组是实现它的方法

return array('artists' => $artists, 'songtoid' => $songtoid, 'artisttoid' => $artisttoid);

答案 1 :(得分:1)

我建议您在属性中返回包含所需项目的对象。 要返回一个对象,首先需要一个类:

class MyClass {
    private $artists;
    private $songtoid;
    private $artisttoid;

    public function __construct($arg1, $arg2, $arg3){
        $this->artists = $arg1;
        $this->songtoid = $arg2;
        $this->artisttoid = $arg3;
    }

    public function getArtists(){return $this->artists;}
    public function getSongtoid(){return $this->songtoid;}
    public function getArtisttoid(){return $this->artisttoid;}
}

在你的功能中

function getArtistsBySongId(){
    ...
    return new MyClass($artists, $songtoid, $artisttoid);
}

你也可以像这样返回一个关联数组

return array(
    "artists"=>$artists,
    "songtoid"=>$songtoid,
    "artisttoid"=>$artisttoid
);

或者,如果你愿意,你可以返回一个数组(如Machavity所回答)并使用list()

读取结果
function getArtistsBySongId(){
    ...
    return array($artists, $songtoid, $artisttoid);
}

list($artists, $songtoid, $artisttoid) = getArtistsBySongId();