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

获取关联 - 每个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!

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')