George
George

Reputation: 1112

How to format data in specific way using html and php

I have a table that contains Aspiring team for particular positions and various vote casted. The data is below

Teamtable
|   no  |   team    |   position    |   votes Cast  |
|   1   |   A       |   President   |    2          |
|   3   |   B       |   President   |    1          |
|   4   |   C       |   Secretary   |    2          |
|   6   |   D       |   Secretary   |    1          |

I want to be able to get this in an html format using php and mysql just as below

EXPECTED VIEW IN THE HTML AND PHP FORMAT

    PRESIDENT
Team    |   Total Votes |   Percentage  |
 A      |       2       |   66.67       |
 B      |       1       |   33.33       |

    SECRETARY
Team    |   Total Votes |   Percentage  |
 C      |       2       |   66.67       |
 D      |       1       |   33.33       |

This is what i have tried so far

//QUERY
$SQL=SELECT 
        `team`,
        `position`,
        `votesCast`
    FROM
        Teamtable

$Results=$db->query($SQL);

$data=array();

while($row=mysqli_fetch_assoc($Results)){

    $team=$row['team'];
    $position=$row['position'];
    $totalVote=$row['votesCast'];

    $data[$position][]=$position;
    $data1[$position][]=$team;
    $data2[$position][]=$totalVote;
}

foreach($data as $position =>$electionResults){
    $teams=$data1[$position];
    $totalVotes=$data2[$position];

    foreach($teams as $re => $teas){
        $votes=$totalVotes[$re];
        echo "
            <table>
             <tr>
                <td>$teas</td>
                <td>$votes</td>
             </tr>
            </table>";
    }

}   

I have to tried up to this point, any help is appreciated.

Upvotes: 0

Views: 89

Answers (2)

user789456
user789456

Reputation: 173

This could be very helpful for you

while($row = mysqli_fetch_assoc($result)) {
  $data[$row['position']]['total'][]=$row['votes'];
  $data[$row['position']][]=$row;
}
foreach($data as $k=>$v){
    echo '<p>'.$k.'</p>';
    echo '<table border="1">';
    $total_votes=array_sum($v['total']);
    foreach($v as $kk=>$vv){
        if($kk!=='total'){
            $percentage=round($vv['votes']/$total_votes*100,2);
            echo '<tr><td>'.$vv['tean'].'</td><td>'.$vv['votes'].'</td><td>'.$percentage.'%</td></tr>';
        }
    }
    echo '</table>';
}

Upvotes: 1

Knarf
Knarf

Reputation: 1273

You wan't to have the table on the outside of the foreach.

echo "<table>";
foreach($teams as $re => $teas){
    $votes=$totalVotes[$re];
    echo "<tr>
            <td>$teas</td>
            <td>$votes</td>
         </tr>";
}
echo "</table>";

Upvotes: 0

Related Questions