我一直在努力想出最好的方法来输出金融交易的分页结果和运行总计,首先是最近的交易,最后是第一个(最旧的)交易,但无法似乎找到了一种有效的方法。
单独使用 OFFSET 和 LIMIT 提取结果是行不通的,因为我正在尝试显示运行总计。
出于绝望,我最终选择了一个多维数组,其中主数组中的每个数组都包含 x 个条目,并通过调用每个条目 block 来访问结果(例如,$transArr[0] 将包含前 38 条记录,$transArr[1] 接下来的 38 条,等等)。我确信这是一种非常低效的处理方式,我会喜欢任何和所有建议。
这是我想出的 - 抱歉,它有很多代码,包括分页链接和数据格式。这只是一个类中的一个对象。
public function fetchTransactionsDev($currPage = null) {
global $db;
//Balance the account, set accountBalance variable
$this->balanceAccount();
$accountBalance = $this->accountBalance;
$runningTotal = $accountBalance; //Start the Running Total as the balance
$prevAmount = 0; //Starts at 0, will be used to calculate running total below
//Fetch number of rows and calculate number of pages for paginated links
$numRows = $db->query("SELECT COUNT(*) FROM transactions");
$numRows = $numRows->fetchColumn();
$this->totalTrans = $numRows;
//Number of rows to display per page
$rowsPerPage = 35;
//Find out total pages, factoring in that the array starts at 0
$totalPages = ceil($numRows / $rowsPerPage) - 1;
//Get current page or set default
if (isset($currPage) && is_numeric($currPage)) {
$currentPage = (int) $currPage;
} else {
$currentPage = 0;
}
//Set $currPage to $totalPages if greater than total
if ($currentPage > $totalPages) {
$currentPage = $totalPages;
}
if ($currentPage < 1) {
$currentPage = 0;
}
//Offset of the list, based on current page
$offset = ($currentPage - 1) * $rowsPerPage;
//Array to hold transactions; counters for number of arrays and number of entries per array
$transArr = array();
$arrCount = 0;
$i = 0;
//Fetch the transactions
$sql = "SELECT amount, payee, cat, date FROM transactions ORDER BY id DESC, date DESC";
$fetchTransactionsSQL = $db->query($sql);
while ($transactionDetails = $fetchTransactionsSQL->fetch()) {
$date = date("m/d", strtotime($transactionDetails['date']));
$payee = stripslashes($transactionDetails['payee']);
$category = $transactionDetails['cat'];
$amount = $transactionDetails['amount'];
$runningTotal -= $prevAmount;
$amountOutput = money_format("%n", $amount);
$runningTotalOutput = money_format("%n", $runningTotal);
//Add new array to $transArr with a maximum of x num entries
if ($i <= $rowsPerPage) {
$transArr[$arrCount][] = array("date" => $date, "payee" => $payee, "category" => $category,
"amountOutput" => $amountOutput, "runningTotalOutput" => $runningTotalOutput);
$i++;
} else {
//If over x number of entries, start a new array under $transArr and reset increment counter
$arrCount++;
$i = 0;
$transArr[$arrCount][] = array("date" => $date, "payee" => $payee, "category" => $category,
"amountOutput" => $amountOutput, "runningTotalOutput" => $runningTotalOutput);;
}
if ($arrCount > $currentPage) {
break;
}
$prevAmount = $amount; //Needed for calculating running balance
}
//Output the results to table
foreach ($transArr[$currentPage] as $transaction) {
echo "
<tr>
<td>{$transaction['date']}</td>
<td><strong>{$transaction['payee']}</strong></td>
<td>{$transaction['category']}</td>
<td>{$transaction['amountOutput']}</td>
<td>{$transaction['runningTotalOutput']}</td>
</tr>
";
}
//Create paginated links
if ($currentPage > 0) {
$prevPage = $currentPage - 1;
$this->pageLinks = "<a href='{$_SERVER['PHP_SELF']}?currentPage=$prevPage'>Prev</a>";
}
if ($currentPage != $totalPages) {
$nextPage = $currentPage + 1;
$runningBal = $runningTotal - $prevAmount;
$this->pageLinks .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$nextPage'>Next</a>";
}
}
再次感谢您的任何建议!
更新
根据提供的答案,这是我更新的 SQL。这显示了正确的运行余额(运行余额 = 运行余额 - 之前的金额),但我无法尝试创建分页结果。
$dough = new doughDev;
$dough->balanceAccount();
$accountBalance = $dough->accountBalance;
$setRunning = $db->query("SET @running := $accountBalance, @prevAmount = 0");
$getRunning = $db->query("SELECT amount, @running := @running - @prevAmount AS running, @prevAmount := amount AS prevAmount FROM transactions ORDER BY id DESC, date DESC");
最佳答案
这有点难看,但您可以让 MySQL 使用一些服务器端变量为您计算总计。您希望按照从最近到最旧的顺序列出交易这一事实有点麻烦,但很容易处理:
初始化一个变量:
SELECT @running := 0;
主要查询:
SELECT amount, @running := @running + amount AS running, payee, cat, date
FROM ...
ORDER BY date ASC
这将按日期远期顺序计算运行总数。然后将其包装在另一个查询中,以反转排序顺序并应用限制子句
SELECT amount, running, payee, cat, date
FROM (
... previous query here ...
) AS temp
ORDER BY date DESC
LIMIT $entries_to_show, $offset
这有点低效,因为内部查询将获取整个表以便计算运行总计,然后外部查询将删除除 $offset 值以外的所有行以仅显示该“页面”。
关于php - 带有总计的分页结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7957323/
导读语言模型给我们的生产生活带来了极大便利,但同时不少人也利用他们从事作弊工作。如何规避这些难辨真伪的文字所产生的负面影响也成为一大难题。在3月9日智源Live第33期活动「DetectGPT:判断文本是否为机器生成的工具」中,主讲人Eric为我们讲解了DetectGPT工作背后的思路——一种基于概率曲率检测的用于检测模型生成文本的工具,它可以帮助我们更好地分辨文章的来源和可信度,对保护信息真实、防止欺诈等方面具有重要意义。本次报告主要围绕其功能,实现和效果等展开。(文末点击“阅读原文”,查看活动回放。)Ericmitchell斯坦福大学计算机系四年级博士生,由ChelseaFinn和Chri
使用rspec-rails3.0+,测试设置分为spec_helper和rails_helper我注意到生成的spec_helper不需要'rspec/rails'。这会导致zeus崩溃:spec_helper.rb:5:in`':undefinedmethod`configure'forRSpec:Module(NoMethodError)对thisissue最常见的回应是需要'rspec/rails'。但这是否会破坏仅使用spec_helper拆分rails规范和PORO规范的全部目的?或者这无关紧要,因为Zeus无论如何都会预加载Rails?我应该在我的spec_helper中做
假设我有一个类A,里面有一些方法。假设stringmethodName是这些方法之一,我已经知道我想给它什么参数。它们在散列中{'param1'=>value1,'param2'=>value2}所以我有:params={'param1'=>value1,'param2'=>value2}a=A.new()a.send(methodName,value1,value2)#callmethodnamewithbothparams我希望能够通过传递我的哈希以某种方式调用该方法。这可能吗? 最佳答案 确保methodName是一个符号,而
当我进入Rails控制台时,我已将pry设置为加载代替irb。我找不到该页面或不记得如何将其恢复为默认行为,因为它似乎干扰了我的Rubymine调试器。有什么建议吗? 最佳答案 我刚发现问题,pry-railsgem。忘记了它的目的是让“railsconsole”打开pry。 关于ruby-on-rails-带有Pry的Rails控制台,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/question
我了解instance_eval和class_eval之间的基本区别。我在玩弄时发现的是一些涉及attr_accessor的奇怪东西。这是一个例子:A=Class.newA.class_eval{attr_accessor:x}a=A.newa.x="x"a.x=>"x"#...expectedA.instance_eval{attr_accessor:y}A.y="y"=>NoMethodError:undefinedmethod`y='forA:Classa.y="y"=>"y"#WHATTT?这是怎么回事:instance_eval没有访问我们的A类(对象)然后它实际上将它添加到
据我们所知,Jekyll默认分页仅支持index.html,我想创建blog.html并在那里包含分页。有什么解决办法吗? 最佳答案 如果您创建一个名为/blog的目录并在其中放置一个index.html文件,那么您可以向_config.yml表示paginate_path:"blog/page:num"。不是使用根文件夹中的默认index.html作为分页器模板,而是使用/blog/index.html。分页器将根据需要生成类似/blog/page2/和/blog/page3/的页面。这将使您到达yourwebsite.com/b
我在一个简单的RailsAPI中有以下Controller代码:classApi::V1::AccountsControllerehead:not_foundendendend问题在于,生成的json具有以下格式:{id:2,name:'Simpleaccount',cash_flows:[{id:1,amount:34.3,description:'simpledescription'},{id:2,amount:1.12,description:'otherdescription'}]}我需要我生成的json是camelCase('cashFlows'而不是'cash_flows'
在Ruby(或Rails)中,我们可以做到new_params=params.merge({:order=>'asc'})现在new_params是一个带有添加键:order的散列。但是是否有一行可以返回带有已删除key的散列?线路new_params=params.delete(:order)不会工作,因为delete方法返回值,仅此而已。我们必须分3步完成吗?tmp_params=paramstmp_params.delete(:order)returntmp_params有没有更好的方法?因为我想做一个new_params=(params[:order].blank?||para
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我来自C、php和bash背景,很容易学习,因为它们都有相同的C结构,我可以将其与我已经知道的联系起来。然后2年前我学了Python并且学得很好,Python对我来说比Ruby更容易学。然后从去年开始,我一直在尝试学习Ruby,然后是Rails,我承认,直到现在我还是学不会,讽刺的是那些打着简单易学的烙印,但是对于我这样一个老练的程序员来说,我只是无法将它
如何使用rubyonrails获取网络上某处其他网站的页面数据? 最佳答案 您可以使用httparty只是获取数据示例代码(来自example):requireFile.join(dir,'httparty')require'pp'classGoogleincludeHTTPartyformat:htmlend#google.comredirectstowww.google.comsothisislivetestforredirectionppGoogle.get('http://google.com')puts'','*'*7