I am getting an array through an API I want to show the values in an unordered list. I'm able to access the values individually but unable to create a loop so all the values can show in a list format.
This is how the array looks
Array
(
[0] => Array
(
[students] => Array
(
[0] => Array
(
[name] => Sam
[marks] => 75
)
[1] => Array
(
[name] => Roy
[marks] => 60
)
[2] => Array
(
[name] => Josh
[marks] => 85
)
[3] => Array
(
[name] => Ryan
[marks] => 45
)
[4] => Array
(
[name] => Dev
[marks] => 68
)
)
)
)
I want to create a list like this
<ul>
<li>Sam 75</li>
<li>Roy 60</li>
<li>Josh 85</li>
<li>Ryan 45</li>
<li>Dev 68</li>
</ul>
How can I create a loop to show the values like this in PHP. Any help or suggestion would be very helpful.
CodePudding user response:
<?php
$data = [['students' => [ ... ]]];
$students = $data[0]['students'];
echo "<ul>";
foreach ($students as $student) {
echo "<li>{$student['name']} {$student['marks']}</li>";
}
echo "</ul>";
CodePudding user response:
Just loop with foreach
$data = [[
'students' =>
[
['name' => 'Sam', 'marks' => '75'],
['name' => 'Roy', 'marks' => '60'],
['name' => 'Josh', 'marks' => '85'],
['name' => 'Ryan', 'marks' => '45'],
['name' => 'Dev', 'marks' => '68'],
],
]];
echo "<ul>\n";
foreach($data['0']['students'] as $student) {
echo "<li>{$student['name']} {$student['marks']}</li>\n";
}
echo "</ul>\n";
and this will give you the structured HTML.
<ul>
<li>Sam 75</li>
<li>Roy 60</li>
<li>Josh 85</li>
<li>Ryan 45</li>
<li>Dev 68</li>
</ul>