dongyihao1099 2013-07-06 14:32
浏览 15
已采纳

获取关联 - 每个ID一次向数组添加数据

I'm querying a simple database and I'm using the following PHP code...

while ($row = $results->fetch_assoc()) {

    if($row["status"] == 1) {
        $total[] = $row["to_win"];
    }

    print_r($total);

}

The current data structure looks like this...

id          to_win          status
1           1200.00         1
2           238.94          2
3           1850.57         1
4           55.00           2
5           127.85          2

The problem is it seems that each time it gets another row, it adds the $total to the array. As a result, my print_r is this...

Array ( [0] => 1200.00 ) Array ( [0] => 1200.00 ) Array ( [0] => 1200.00 ) Array ( [0] => 1200.00 [1] => 1850.57 ) Array ( [0] => 1200.00 [1] => 1850.57 ) Array ( [0] => 1200.00 [1] => 1850.57 ) Array ( [0] => 1200.00 [1] => 1850.57 ) Array ( [0] => 1200.00 [1] => 1850.57 )

Could I just have it add it one time per ID so that the array would contain one 1200.00 and one 1850.57 rather than multiple entries?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongzhun4898 2013-07-06 14:35
    关注

    The result is as expected. But I guess you want to place the print_r() outside of the loop: ;)

    while ($row = $results->fetch_assoc()) {
        if($row["status"] == 1) {
            $total[] = $row["to_win"];
        }
    }
    
    print_r($total);
    

    But however, as this was easy, I'll give you another advice. Results that are coming from database queries are strings although the SQL column type might be INTEGER. Although in this short example it will work as you wish it is a good practice to check for the correct type. So the statement should be:

    if($row["status"] === '1')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上