如何使用数组来存储从php中的sql查询获取值

时间:2011-02-06 02:20:11

标签: php sql arrays

我想在这里做的是能够将sql查询中的值分配给数组。 然后计算总数。

<?php

include('conn.php');

$qreports=query_database("SELECT S_PRICE, PID, QTY_PUR, ITEM_ID, CUSID, CNUM, Cust_Name, TDATE  FROM prod_table, customer_credit, sales_trans_items WHERE prod_table.PID=sales_trans_items.ITEM_ID AND sales_trans_items.CNUM=customer_credit.CUSID AND sales_trans_items.TDATE='2011-02-06 09:14:09'","onstor",$link);

$grandtotal=0;

$customer="";
while($qrep=mysql_fetch_assoc($qreports)){


    $pid=$qrep['PID'];

    foreach ($pid as $k => $v) {
    $sids=$v;
    $qtypur=$qrep['QTY_PUR'][$k];
    $sprice=$qrep['S_PRICE'][$k];
    $customer=$qrep['Cust_Name'][$k];
    $tdate=$qrep['TDATE'][$k];


    $stot=$qtypur * $sprice;

    $grandtotal =$grandtotal + $stot;
}

}

echo "Customer: ". $customer."<br/>";
echo "Profit: ". $grandtotal;

&GT?;

我在phpmyadmin上尝试查询,然后将其放入代码中,并输出: enter image description here

2 个答案:

答案 0 :(得分:2)

我认为您误解了mysql_fetch_assoc的工作方式:每次调用都会从结果集中返回一行$greparray,其结构为columnname => value

这也意味着$qrep['PID']不能是一个数组而你的foreach循环不起作用。在每个循环中,$qrep['PID']包含您在屏幕截图的PID列中看到的值之一。

我建议您在print_r($qreq);循环中添加while,以便更熟悉数组的结构。

由于每个$qrep本身就是一个数组,因此创建结果数组只是将每个数组添加到一个新数组中:

$result = array();
while(($qrep=mysql_fetch_assoc($qreports))) {
    $result[] = $qrep;
}

现在你正在执行一些更多的计算,我不知道你最终想要得到什么,但似乎你将每个QTY_PS_PRICE相乘:

$total = 0;
foreach($result as $report) {
    $total += $report['QTY_P'] * $report['S_PRICE'];
}

(你也可以在你的while循环中计算它)

假设您想获得每个客户的总和和总和:

$total = 0;
$total_per_customer = array();
foreach($result as $report) {
    $customer = $report['Cust_Name'];
    if(!array_key_exists($customer, $total_per_customer)) {
        $total_per_customer[$customer] = 0;
    }
    $price = $report['QTY_P'] * $report['S_PRICE'];
    $total_per_customer[$customer] += $price;
    $total += $price;
}

最后,$total_per_customer是一个数组,其客户名称为键,价格总和为值。 $total将包含所有价格的总和。

答案 1 :(得分:1)

你的问题有点不清楚,但我认为答案不会远离以下建议的参考文献:

  • 当您循环使用行时 像$array[] = $qrep['columnName']这样的东西来填充 阵列。
  • 然后,查看PHP's array_sum()