暮色呼如
获取表格的唯一距离和名称。$names = array_unique(array_map(fn($a) => $a['name'], $data));$dists = array_unique(array_map(fn($a) => $a['distance'], $data));制作一个按名称和距离查找表值的函数。function findValue($dist, $name, $data): string { foreach($data as $d) { if($d['name'] != $name || $d['distance'] != $dist ) continue; return (string) $d['value']; } return '';}现在输出以头部和距离开头的表格echo "<table>\n";echo "<tr><th></th>", implode('', array_map(fn($col) => "<th>$col</th>", $dists)), "</tr>\n";使用我们的 find 函数逐行列出每个名称的数据foreach($names as $name) { $row = []; foreach($dists as $dist) { $row[] = '<td>' . findValue($dist, $name, $data) . '</td>'; } $rowText = join('', $row); echo "<tr><td>$name</td>$rowText</tr>\n";}最后关上桌子。echo "</table>\n";结果是<table><tr><th></th><th>60</th><th>100</th><th>200</th><th>400</th></tr><tr><td>Alexander</td><td>9</td><td>10</td><td>11</td><td>12</td></tr><tr><td>Dmitriy</td><td>5</td><td>6</td><td>7</td><td>8</td></tr><tr><td>Sergei</td><td>1</td><td>2</td><td>3</td><td>4</td></tr></table>
饮歌长啸
我们必须先重组数组$array = Array( "0" => Array ( "name" => "Alexander", "distance" => 60, "value" => 9 ), "1" => Array ( "name" => "Alexander", "distance" => 100, "value" => 10 ), "2" => Array ( "name" => "Alexander", "distance" => 200, "value" => 11 ), "3" => Array ( "name" => "Alexander", "distance" => 400, "value" => 12 ), "4" => Array ( "name" => "Dmitriy", "distance" => 60, "value" => 5 ), "5" => Array ( "name" => "Dmitriy", "distance" => 100, "value" => 6 ), "6" => Array ( "name" => "Dmitriy", "distance" => 200, "value" => 7 ), "7" => Array ( "name" => "Dmitriy", "distance" => 400, "value" => 8 ), "8" => Array ( "name" => "Sergei", "distance" => 60, "value" => 1 ), "9" => Array ( "name" => "Sergei", "distance" => 100, "value" => 2 ), "10" => Array ( "name" => "Sergei", "distance" => 200, "value" => 3 ), "11" => Array ( "name" => "Sergei", "distance" => 400, "value" => 4 ));$table_heading = array_unique(array_column($array, "distance"));$restructured_array = [];foreach($array as $row){ if(!isset($restructured_array[$row["name"]])){ $restructured_array[$row["name"]] = []; } $restructured_array[$row["name"]][$row["distance"]] = $row["value"];}现在可以循环数组以打印表格。echo "<table><thead><tr>";echo "<th></th>";foreach($table_heading as $heading){ echo "<th>".$heading."</th>";}echo "</tr></thead>";echo "<tbody>"; foreach ($restructured_array as $key=>$rows){ echo "<tr><th>".$key."</th>"; foreach ($rows as $k=>$row){ echo "<td>".$row."</td>"; }}echo "</tbody></table>";输出将是 60 100 200 400Alexander 9 10 11 12Dmitriy 5 6 7 8Sergei 1 2 3 4