首先,我是一名php新手...因此,我仍然会编程和理解php。那就是
我有一个存储在数据库中的数字(金额)集合。
问题:使用PHP和mySQL,
什么是从数据库中后台存储此信息的最佳方法,以使金额与其交易ID相关联
最重要的是,我需要在db中找到一个匹配的数字集,其总和为29。
以下是Transaction_tlb
我的数据库的交易表,mydb
Transaction_ID | Name | Date | Amount
---------------|------------------|-----------------|------------
11012 | Jonathan May | 6/12/2016 | 84
21012 | John Pedesta | 6/12/2016 | 38
31012 | Mary Johnson | 1/01/2017 | 12
41012 | John Johnson | 8/01/2017 | 13
51012 | Keith Jayron | 8/01/2017 | 17
61012 | Brenda Goldson | 8/01/2017 | 2
71012 | Joshua Traveen | 8/01/2017 | 78
81012 | Remy ma Goldstein| 8/01/2017 | 1
91012 | Barbie Traveen | 8/01/2017 | 1
现在,我有一个主意..但效率不高。我将尝试所有可能的情况。这意味着如果我要检查n个值,则时间复杂度将约为2 ^ n。这是非常低效的(另外,我什至不知道我的代码是否有意义。(请参阅下文)
我在以下YouTube视频中看到了类似的示例:https : //www.youtube.com/watch?v=XKu_SEDAykw&t
但是,我不确定确切如何在php中编写代码。
编码:
<?php
if (!mysql_connect("localhost", "mysql_user", "mysql_password") || !mysql_select_db("mydb")) {
die("Could not connect: " . mysql_error()); } //End DB Connect
$capacity = 29; //Knapsack Capacity or Sum
//Select Transact ID and Value from the Database where Amount is <= Capacity
$fetchQuery = "SELECT 'Transaction_ID', 'Amount' FROM 'Transaction_tlb' WHERE 'Amount' <= $capacity";
$components = array(); //new array to hold components
if ($queryResults = mysql_query($fetchQuery)) {
//check if data was pulled
if (mysql_num_row($queryResults) != NULL) {
while ($row = mysqli_fetch_assoc($queryResults) {
$components[$row['Transaction_ID']] = $row['Amount'];
}
}
}
/* Correct me if i am wrong, but, Components associative array Should be something like
$components = array('11012'=> 84, '21012'=> 38, '31012'=> 12, '41012'=> 13, '51012'=> 17,
'61012'=> 2, '71012'=> 78, '81012'=> 1, '91012'=> 1);
*/
$components = asort($components) // sort array in ascending order
$componentCount = count($component)
function match ($componentCount, $capacity) {
$temp = match (($componentCount - 1), $capacity);
$temp1 = $component[$componentCount] + match (($componentCount - 1), ($capacity - $component[$componentCount]));
$result = max($temp, $temp1);
return $result;
}
}?>
谁能给我指出正确的方向?该代码不起作用...即使它起作用...该方法也根本无效。我有300万条记录可以使用时会发生什么?我需要帮助。
您可以根据0/1背包问题来表达问题。提供了PHP中的即用型实现。
使用knapSolveFast2
链接页面中定义的功能,可以按以下示例进行操作。这里的想法是,将输入背包算法的“权重”设置为等于值本身。
$components = array(84, 38, 12, 13, 17, 2, 78, 1, 1);
$m = array();
list($m4, $pickedItems) = knapSolveFast2($components, $components, sizeof($components)-1, 29, $m);
echo "sum: $m4\n";
echo "selected components:\n";
foreach($pickedItems as $idx){
echo "\t$idx --> $components[$idx]\n";
}
产生:
sum: 29
selected components:
2 --> 12
4 --> 17
笔记:
amount
大于所需总和的行(29)$m4
是否确实等于指定的总和(29)-随着算法的工作,指定的数量只是不能保证达到的上限(例如,返回值不是37,而不是29只有34,因为没有输入数字的组合,其总和将得出37)本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句