php 查找数字,PHP:在数据库中查找一组总和特定数字的数字

首先,我是一个

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万条记录可以使用时会发生什么?我需要帮助.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值