PHP print SQL field names as array with correspond

2019-09-09 10:22发布

问题:

Have a SQL table like this:

Titles  Device1 Device2 Device3
Title1  inputA  inputA  inputB
Title2  inputA  inputB  inputC
Title3  inputB  inputB  inputB

I want the values inputA, inputB, inputC to each appear once in each row with their corresponding fields, Device1, Device2, Device3, appearing as an array following the "input" values like this:

Titles  header1 header2 header3
Title1  inputA: inputB:
        Device1 Device3
        Device2 
Title2  inputA: inputB: inputC:
        Device1 Device2 Device3
Title3  inputB:
        Device1
        Device2
        Device3

This is what I've got so far after a custom header and SELECT statement:

$myquery = $mysqli->query ($sqlSelect);
if ($myquery = $mysqli->query ($sqlSelect)) { 
  while($row = mysqli_fetch_assoc($myquery)){
    $format=array();
    foreach ($row as $key => $val) {
      switch($key) {
        case "Device1":
        case "Device2":
        case "Device3":
          $format[$val] = "<br>".$key;   
          break;
      }
   }
   printf ("<tr><td>%s</td>", $row["Titles"]);
   foreach ($format as $key => $val) {
     printf ("<td>$key:<br/>$val</td>");
   }
   printf ("</tr>");
 }

But don't know how to get all "Device" fields to display with their corresponding values. Looks like this:

Titles  header1 header2 header3
Title1  inputA: inputB: 
        Device1 Device3 
Title2  inputA: inputB: inputC:
        Device1 Device2 Device3
Title3  inputB:
        Device1

The only time more than one Device field appeared in a cell was when there were no values in a row with a title. Missing something before break? A while statement?

回答1:

First of all it is easier to first convert your data to a format you can more easily output. Following a little example:

$result = array();
while($row = mysqli_fetch_assoc($myquery)){
    $tmp = array();
    foreach (array('Device1', 'Device2', 'Device3') as $key) {
        if (!isset($tmp[$row[$key]])) $tmp[$row[$key]] = array();

        $tmp[$row[$key]][] = $key;
    }

    $result[$row['Titles']] = $tmp;
}

Now you can output a correct html table (including empty trailing cells):

$max = 0;
foreach ($result as $title => $inputs) {
    $max = max($max, count($inputs));
}

print('<table>');
print('<tr><td>Titles</td><td>header1</td><td>header2</td><td>header3</td></tr>');
foreach ($result as $title => $inputs) {
    print('<tr><td>' . $title . '</td>');

    foreach ($inputs as $input => $devices) {
        print('<td>' . $input . '<br/>' . implode('<br/>', $devices) . '</td>');
    }

    // fill with empty cells
    for ($i = 0; $i < $max - count($inputs); ++$i) {
        print('<td></td>');
    }

    print('</tr>');
}
print('</table>');