Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

php - i have 2 tables (expenses , expdescription) my question is how to show expenses in table grouped by expenses description

    while($row = mysqli_fetch_array($query))
       {
        //$sql3 ='select * from description where descid = '.$row['descid'].' ';
        $query3 = mysqli_query($conn,$sql3);
        $row2 = mysqli_fetch_array($query3);
        $total =$total + $row['amount'];
        echo ' <tr>
        <td style="text-align:center">'.$row['amount'].'</td>
        <td style="text-align:center">'.$row2['description'].'</td>
        <td style="text-align:center">'.$row['info'].'</td>
        <td style="text-align:center">'.$row['DATE'].'</td>
        <td style="text-align:center">'.$total.'</td>';

      
        ?>
        <td><a href="insert.php?delete=<?php echo $row['outid']; ?>"
        class ="btn btn-danger">delete</a></td>
        <?php
        echo '
        </tr>';
       
     }
    } 

this code show me all data from expenses table but how to write php code to . show all expenses grouped by expense description .

question from:https://stackoverflow.com/questions/65840837/i-have-2-tables-expenses-expdescription-my-question-is-how-to-show-expenses

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to generate another array grouped by description or just query another SQL statement, that reads out the grouped rows. Since you have all the data queried already I 'd suggest a simple array grouped by description.

$grouped = [];
$data = mysqli_fetch_array($query);

foreach ($data as $row) {
    if (!isset($grouped[$row['description'])) {
        $grouped[$row['description]] = 0;
    }

    $grouped[$row['description'] += $row['amount'];
}

// process your templating here
foreach ($data as $row) {
    ...
}

Anayway ... another solution could be a simple SQL Statement.

SELECT SUM(amount) AS sum FROM table WHERE description_id = :description_id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...