返回值从PHP函数
问题描述:
我试图返回值作为数组,但未能阵列,返回值从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,但不能让我的头围绕这个
答
马丁是对他的回答,我只想补充一些解释。
在你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;
}
如何设置while循环,它将无限运行,直到sc撕裂时间了。你永远不会得到回报。 –
是[while循环(http://php.net/manual/en/control-structures.while.php)看起来不正确 – 2pha
不能发布整个代码,这是我的最终完全好了, – Shehary