从PHP函数返回值作为数组

时间:2016-02-28 23:24:46

标签: php arrays 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尝试了几个解决方案,但无法理解这个

2 个答案:

答案 0 :(得分:1)

你想做点什么:

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;
}

答案 1 :(得分:1)

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

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'];
}