首先,我是一个
PHP新手…所以我仍然编程和理解PHP程序.那说,
我有一个存储在数据库中的数字(数量)的集合.
问题:使用PHP和mySQL,
>什么是将此信息从数据库中取出的最佳方法,以使金额与其交易ID相关联
>最重要的是,我需要在db中找到一组匹配的数字,等于29的总和.
下面是我的数据库mydb的事务表Transaction_tlb
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.这是非常低效的(另外,我甚至不知道我的代码是否有意义.(见下文)
但是,我不确定如何在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万条记录可以使用时会发生什么?我需要帮助.