Reputation: 21721
I have:
$l = array(
array("A"=>0.1,"B"=>1,"C"=>1,"D"=>1),
array("A"=>0.1,"B"=>1,"C"=>0,"D"=>2),
);
$h = array('h1','h2');
1-How Can I map(l,h)
to this?
$result= $array(
'h1'=> array("A"=>0.1,"B"=>1,"C"=>1,"D"=>1),
'h1'=> array("A"=>0.1,"B"=>1,"C"=>0,"D"=>2),
);
2- So I I can display(present html table)
-------------------
| A | B | C | D
-------------------
h1 |
-------------------
h2 |
--------------------
My trying to output:
<table>
<tr><td>A</td><td>B</td><td>C</td><td>D</td></tr>
foreach($result as $key=>$value){
<tr>
<tr>
}
<table>
Anybody can help me?
Upvotes: 0
Views: 634
Reputation: 437414
Mapping the array as you propose is easy:
$mapped = array_combine($h, $l);
Then:
// Print the top "headers" row
$columns = array_keys(reset($l));
echo '<table><tr><td> </td>';
foreach ($columns as $column) {
echo '<td>'.$column.'</td>';
}
echo '</tr>';
// Print each data row
foreach ($mapped as $key => $row) {
echo '<tr><td>'.$key.'</td>';
foreach ($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
// Done!
echo '</table>';
Upvotes: 5
Reputation: 16768
$result = array_combine($h, $l);
This works bc there are implied numeric indexes for the array elements, as you can see if you var_dump($h)
or var_dump($l)
<table>
<?php
echo "<tr>";
echo "<td> </td>";
foreach(array_keys($l[0]) as $letter)
echo "<td>$letter</td>"; //A,B,C,D
echo "</tr>";
foreach($result as $h_key=>$innerArr)
{
echo "<tr><td>$hkey</td>"; //h1,h2
foreach($innerArr as $key=>$val)
echo "<td>$val</td>"; //0.1, 1, etc.
echo "</tr>";
}
?>
</table>
Upvotes: 0