从 PHP 函数返回值作为数组


return values as arrays from PHP function

我正在尝试将值作为数组返回,但失败了,

函数调用

$rates = getamount($Id, $days, $date, $code);

功能

function getamount($Id, $days, $date, $code) {
    // fetch data from database
    // run whileloop
    while() {
        // Do other stuff
        // Last get final output values
        $rates['id'] = $finalid;
        $rates['days'] = $finaldays;
        // more and more
        $rates['amount'] = $finalamount;
        //If echo any variable here, can see all values of respective variable.
    }
    //If echo any variable here, can only see last value.
    return $rates;
}

最后在函数之外(也需要这个,所以将变量也作为数组加载到会话中)

$compid = $rates['id'];
$totaldays = $rates['days'];
$totalamount = $rates['amount'];

尝试了SO的几个解决方案,但无法解决这个问题

马丁的回答是对的,我只想补充一些解释。

while 循环中,您将覆盖相同的数组,因此在最后,它将包含数据库查询结果中最后一行的数据。

要解决这个问题,你需要一个数组数组。每个$rate数组表示数据库中的一行,$rates是这些行的数组:

function getamount($Id, $days, $date, $code)
{
    // fetch data from database
    $rates = []; // initialize $rates as an empty array
    while (whatever) {
        $rate = []; // initialize $rate as an empty array
        // fill $rate with data
        $rate['id'] = $finalid;
        $rate['days'] = $finaldays;
        // more and more
        $rate['amount'] = $finalamount;
        // add $rate array at the end of $rates array
        $rates[] = $rate;
    }
    return $rates;
}

现在尝试检查$rates数组中的内容:

$rates = getamount($Id, $days, $date, $code);
var_dump($rates);

要从数组中获取数据$rates您需要再次循环(与创建它的方式相同):

foreach ($rates as $rate) {
    var_dump($rate);
    // now you can access is as you were trying it in your question
    $compid = $rate['id'];
    $totaldays = $rate['days'];
    $totalamount = $rate['amount'];
}

你想做这样的事情吗:

function getamount($Id, $days, $date, $code) {
    $rates = [];
    while (whatever) {
        $rate = [];
        $rate['id'] = $finalid;
        $rate['days'] = $finaldays;
        // more and more
        $rate['amount'] = $finalamount;
        $rates[] = $rate;
    }
    return $rates;
}