Issue
I have an multidimensional array which I'm trying to output as a table, here is my array;
$marksarray=
array(3) {
[0]=>
array(2) {
[0]=>
string(1) "8"
[1]=>
string(1) "0"
}
[1]=>
array(2) {
[0]=>
string(1) "9"
[1]=>
string(1) "1"
}
[2]=>
array(2) {
[0]=>
string(2) "13"
[1]=>
string(1) "2"
}
}
So far I have my code like this;
echo "<table><tr><td>Question</td><td>Rating</td></tr>";
foreach ($marksarray as $mks){
foreach ($mks as $qid=>$rate){
echo "<tr><td>".$qid."</td><td>".$rate."</td></tr>";
}
}
echo "</table></div>";
But my output is;
What is that i'm doing wrong?
Solution
You've got one too many foreach
's going on there. Try this instead:
echo "<table><tr><td>Question</td><td>Rating</td></tr>";
foreach ($marksarray as $mks){
echo "<tr><td>".$mks[0]."</td><td>".$mks[1]."</td></tr>";
}
echo "</table></div>";
For future reference, it makes your code far easier to understand if you use an array of associative arrays with meaningful keys. e.g.
$marksarray = array(
array('qid' => 8, 'rating' => 0),
array('qid' => 9, 'rating' => 1),
array('qid' => 13, 'rating' => 2)
);
Then your loop would look like this:
foreach ($marksarray as $mark){
echo "<tr><td>".$mark['qid']."</td><td>".$mark['rating']."</td></tr>";
}
Better still, you should use MVC (Model, View, Controller) and pass this data into a view...but that's another subject entirely.
Answered By - RobMasters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.