duankuaiwang2706 2015-04-07 23:05
浏览 22

具有非唯一键的PHP关联数组

Struggling with concept of an associative array that maps userIDs to partIDs and re-order quantity for the part.

We have bunch of parts that I need to re-order, but I must keep track of which user needs what parts re-purchased for them. The list of UserIDs comes from one table, then the inventory_used comes from another table.

Suppose a list like this:

Example One:

UserID   PartID   Qty_Used
    1       3       2
    1       4       7
    2       1       4
    2       4       3
    3       3       5

After creating an array with the above information, I must create a re-order form (table) for the parts. Therefore, ignoring the userID, group them by the partID, and sum up the total Qty (per part). The re-order table should look something like this:

Example Two:

PartID      Qty_to_Reorder
    1        4
    3        7
    4       10

I know I'm going to take a ton of downvotes for failing to show code, but I can't wrap my mind around this seemingly simple problem. (This is for my office, not a school project).

How do I:

(1) Structure the first array (what would the loop to create it look like?), and then

(2) Loop through that array to summarize/group partIDs => Qty for re-order report, as per 2nd example above?


For the first loop, i was thinking of something like this:

Loop through UserIDs {
    Loop through PartIDs {
        $arrReorder[UserID][PartID] = Qty_Used;
    }
}

Is that correct? How would I loop through $arrReorder to sum-up the qty used for each partID, and get the re-order report (example 2)?

  • 写回答

2条回答 默认 最新

  • duanmu2013 2015-04-07 23:37
    关注

    SELECT SUM(Qty_Used) AS total FROM mytable WHERE PartID=3

    PS: Using PHP

    <?php
        $data = array();
        $data[] = array("UserID" => 1, "PartID" => 3, "Qty_Used" => 2);
        $data[] = array("UserID" => 1, "PartID" => 4, "Qty_Used" => 7);
        $data[] = array("UserID" => 2, "PartID" => 1, "Qty_Used" => 4);
        $data[] = array("UserID" => 2, "PartID" => 4, "Qty_Used" => 3);
        $data[] = array("UserID" => 3, "PartID" => 3, "Qty_Used" => 5);
    
        $PartID = 3;
        $sum = 0;
    
        foreach ($data as $arr) {
    
            if ($arr['PartID'] == $PartID)
                $sum += $arr['Qty_Used'];
        }
    
        echo $PartID."\t".$sum."
    ";
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度