douyin4875 2015-07-24 22:58
浏览 39
已采纳

PHP中奇怪的关联数组行为

I am trying to create an associative array in PHP.

The idea is to store an "item Id" as the array key and the total spend on that item Id as the value.

I am using the following code to get data out of my MYSQL two separate tables, one that contains the item info and one that contains a list of expenses.

    // GET ITEM DATA FROM DB
    $getItemData = mysql_query("SELECT * FROM items;");

    // CREATE ARRAY
    $orderItemsBySpend = array();

    // LOOP THROUGH ITEMS AND CALCULATE SPEND IN LAST 30 DAYS
    while($itemData = mysql_fetch_assoc($getItemData)){ 


        $getItemExpenses = mysql_query("
        SELECT SUM(cost)
        AS productExpenses
        FROM expenses
        WHERE itemId = $itemData[id]
        AND date BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW();");

        $itemExpenses = mysql_fetch_assoc($getItemExpenses);

        // SET TOTAL SPEND VARIABLE
        $totalProductSpend = $itemExpenses['productExpenses'];

        // SET ITEM ID VARIABLE
        $itemId = $itemData[id];

        // ADD KEY AND VALUE TO ARRAY
        $orderItemsBySpend[$itemId] = $totalProductSpend;

        // PRINT ARRAY FOR TESTING PURPOSES
        print_r($orderItemsBySpend);
    }

Unfortunately instead of getting something like this, as I would expect (and am hoping for!)

Note the 0.00 values are only down to the fact there is only limited data in the expenses table.

Array (
[1] => 14.01
[2] => 0.00
[3] => 0.00
[4] => 0.00
[5] => 0.00
[6] => 20.24
[7] => 0.00
[8] => 0.00
[9] => 0.00
)

Instead I am getting this:

Array ( 
[0] => 14.01
) 

Array ( 
[0] => 14.01
[1] => 0.00
)

Array ( 
[0] => 14.01
[1] => 0.00
[2] => 0.00
)

Array (
[0] => 14.01
[1] => 0.00
[2] => 0.00
[3] => 0.00
) 

etc.

My question is: Why is this strange "incremental pattern" of arrays being created? And why is the array key not being set as the item Id?

The first array should have key of 1 (the first item Id), not 0.

All advice appreciated!

Thanks,

Bruce.

  • 写回答

2条回答 默认 最新

  • dougu4704 2015-07-24 23:08
    关注

    The problem is you are printing your array at wrong place.It is inside loop right now that's whay it is printing in that manner.Just remove it inside while() loop and put it outside loop. Do like below:-

    while(){
    }
    print_r(); 
    

    Note :- An useful suggestion is to switch to mysqli_* or PDO is best, because mysql_* is officially deprecated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改