【发布时间】:2017-07-25 10:20:09
【问题描述】:
首先,我是 php 新手...所以我仍然在程序上编码和理解 php。也就是说,
我有一组数字(数量)存储在数据库中。
问题:使用 PHP 和 mySQL,
从数据库中提取此信息以便金额与其交易 ID 相关联的最佳方法是什么
最重要的是,我需要在数据库中找到一组匹配的数字,等于 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。这是非常低效的(另外,我什至不知道我的代码是否有意义。(见下文)
我在这个 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 万条记录可供使用时会发生什么?我需要帮助。
【问题讨论】:
-
提示:不要在 PHP 中使用 SQL 顺序对值进行排序。顺便说一句,en.wikipedia.org/wiki/Subset_sum_problem 是 NP 完成的。
标签: php algorithm dynamic-programming memoization knapsack-problem