nik1004 nik1004 - 1 month ago 7
PHP Question

Form table from PHP array

I met problem, that, I believe, you can help me with.

I have next array:

JSON:

{
"1":{
"01:00":"1",
"02:00":""
},
"2":{
"01:00":"3",
"02:00":""
},
"3":{
"01:00":"23",
"02:00":""
},
"4":{
"01:00":"234",
"02:00":""
},
"5":{
"01:00":"234",
"02:00":""
},
"6":{
"01:00":"",
"02:00":""
},
"7":{
"01:00":"",
"02:00":""
}
}


PHP:

array (
1 => array ( '01:00' => '1', '02:00' => '', ),
2 => array ( '01:00' => '3', '02:00' => '', ),
3 => array ( '01:00' => '23', '02:00' => '', ),
4 => array ( '01:00' => '234', '02:00' => '', ),
5 => array ( '01:00' => '234', '02:00' => '', ),
6 => array ( '01:00' => '', '02:00' => '', ),
7 => array ( '01:00' => '', '02:00' => '', ),
)


I am trying to put right values to right places, but I am at dead end :(

Can you help me with the table generator for this array.

It should look like this with values in inputs:
enter image description here

First line is quite static:

echo "<table><tr>";
for ($i = 0; $i < 8; $i++) {
echo "<td>$days[$i]</td>";
}
echo "</tr>";


And then problems starts.

Answer

try the following code

<?php
$days = array (
    1 => array ( '01:00' => '1', '02:00' => '', ),
    2 => array ( '01:00' => '3', '02:00' => '', ),
    3 => array ( '01:00' => '23', '02:00' => '', ),
    4 => array ( '01:00' => '234', '02:00' => '', ),
    5 => array ( '01:00' => '234', '02:00' => '', ),
    6 => array ( '01:00' => '', '02:00' => '', ),
    7 => array ( '01:00' => '', '02:00' => '', ),
);

echo "<table border='1'><thead><th>0</th>";

foreach($days as $k=>$v){   
    echo "<th>".$k."</th>"; 
}
echo "</thead><tbody>";

$rows = array_keys($days[1]);//edited

foreach($rows as $row){
    echo "<tr><td>".$row."</td>";
    foreach($days as $key=>$val){
        echo "<td>";
        echo "<input type='text' name='txt".$key."' value='".$days[$key][$row]."' style='width:40px;' />";//edited
        echo "</td>";
    }
    echo "</tr>";
}

echo "</tbody></table>";


?>