I'm currently learning php and I'm trying to print a multidimensional associative array in html table format and I'm having some trouble looping through each of the elements, here's the code
$test =array(
'One'=>array('fname' => 'John', 'lnom' => 'Dupond', 'age' => 25, 'city' => 'Paris'),
'Two' => array('fname' => 'Deal', 'lnom' => 'Martin', 'age' => 20, 'city' => 'Epizts'),
'Three' => array('fname' => 'Martin', 'lnom' => 'Tonge', 'age' => 18, 'city' => 'Epinay'),
'Four'=> array('fname' => 'Austin', 'lnom' => 'Dupond', 'age' => 33, 'city' => 'Paris'),
'Five'=> array('fname' => 'Johnny', 'lnom'=>'Ailta', 'age' => 46, 'city'=> 'Villetaneuse'),
'Six'=> array('fname' => 'Scott', 'lnom' => 'Askier', 'age'=>7, 'city'=>'Villetaneuse')
);
what I'm trying to do :
foreach($test['One'] as $key=> $value)
{
echo $value;
}
I'm not too sure about the rest if I should use a nested foreach loop or something else to print all the keys values ..
CodePudding user response:
If you want to loop through this array completely and turn it to an html table you need two loops - one for the main and second for inner array for example:
<?php
$test =array(
'One'=>array('fname' => 'John', 'lnom' => 'Dupond', 'age' => 25, 'city' => 'Paris'),
'Two' => array('fname' => 'Deal', 'lnom' => 'Martin', 'age' => 20, 'city' => 'Epizts'),
'Three' => array('fname' => 'Martin', 'lnom' => 'Tonge', 'age' => 18, 'city' => 'Epinay'),
'Four'=> array('fname' => 'Austin', 'lnom' => 'Dupond', 'age' => 33, 'city' => 'Paris'),
'Five'=> array('fname' => 'Johnny', 'lnom'=>'Ailta', 'age' => 46, 'city'=> 'Villetaneuse'),
'Six'=> array('fname' => 'Scott', 'lnom' => 'Askier', 'age'=>7, 'city'=>'Villetaneuse')
);
?>
<table>
<tr>
<th>#</th>
<th>fname</th>
<th>lnom</th>
<th>age</th>
<th>city</th>
</tr>
<?php
foreach($test as $key => $val){
?><tr>
<td><?php echo $key;?></td><?php
foreach($val as $k => $v){
?><td><?php echo $v;?></td><?php
}
?></tr><?php
}
?>
</table>
Will return:
# fname lnom age city
One John Dupond 25 Paris
Two Deal Martin 20 Epizts
Three Martin Tonge 18 Epinay
Four Austin Dupond 33 Paris
Five Johnny Ailta 46 Villetaneuse
Six Scott Askier 7 Villetaneuse
CodePudding user response:
Just loop the outer array:
<table>
<?php foreach ($test as $person) { ?>
<tr>
<td><?= $person['fname'] ?></td>
<td><?= $person['lnom'] ?></td>
<td><?= $person['age'] ?></td>
<td><?= $person['city'] ?></td>
</tr>
<?php } ?>
</table>
The variable $person
will contain the sub array, from which you just fetch the elements you want.
If you want to output every column dynamically (not needing to write $person['fname']
etc), then you can create a nested loop:
<?php foreach ($test as $person) { ?>
<tr>
<?php foreach ($person as $value) { ?>
<td><?= $value ?></td>
<?php } ?>
</tr>
<?php } ?>