2016-02-28 128 views
-1

我试图返回值作为数组,但未能阵列,返回值从PHP函数

函数调用

$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,但不能让我的头围绕这个

+0

如何设置while循环,它将无限运行,直到sc撕裂时间了。你永远不会得到回报。 –

+0

是[while循环(http://php.net/manual/en/control-structures.while.php)看起来不正确 – 2pha

+0

不能发布整个代码,这是我的最终完全好了, – Shehary

回答

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

谢谢它的工作 – Shehary

+0

伟大的。你有没有得到这个原则?我认为,如果你检查'$ rates'阵列里面有什么是(使用'的var_dump($率)'它可以帮助你理解它。 –

+0

烨,得到了它,我在很多失踪未初始化内部阵列阵列,感谢结算它 – Shehary

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