我正在使用PHP和MySQL 目前我有这样的数据库结构
EventID | MatchName | Tournament | Results
1234 | match1 | Tour1 | 1-0
5678 | match2 | Tour2 | 0-1
7890 | match3 | Tour1 | 1-2
我需要通过锦标赛对它们进行分组,然后像这样获得每个锦标赛记录
<thead>
<th>Tour1</th>
</thead>
<tr>
<td>1234</td><td>match1</td><td>Tour1</td><td>1-0</td>
<td>7890</td><td>match3</td><td>Tour1</td><td>1-2</td>
</tr>
<thead>
<th>Tour2</th>
</thead>
<tr>
<td>5678</td><td>match2</td><td>Tour2</td><td>0-1</td>
</tr>
答案 0 :(得分:1)
我知道有更简单的方法可以做到你想要的,但是,使用以下库你可以做到你想要的更多:
在以下示例中,您将看到如何执行此操作:
use FunctionalPHP\common\Object;
use FunctionalPHP\common\functional\Collectors;
use FunctionalPHP\iterable\collection\lists\ArrayList;
class Event extends Object {
protected $eventId;
protected $matchName;
protected $tournament;
protected $results;
public function __construct (int $eventId, string $matchName
,string $tournament, string $results) {
$this->eventId = $eventId;
$this->matchName = $matchName;
$this->tournament = $tournament;
$this->results = $results;
}
}
$arrayListOfEvents = new ArrayList();
$arrayListOfEvents->add (new Event (1234, 'match1', 'Tour1', '1-0'));
$arrayListOfEvents->add (new Event (5678, 'match2', 'Tour2', '0-1'));
$arrayListOfEvents->add (new Event (7890, 'match3', 'Tour1', '1-2'));
$hashMap = $arrayListOfEvents->stream()
->collect (Collectors::groupingBy (function (Event $event) : string {
return $event->tournament;
}));
您将能够通过以下方式访问存储的元素:
foreach ($hashMap->iterator() as $internalKey => $internalValue) {
echo "\nKey of current element of Map: ", $internalKey;
foreach ($internalValue->getIterable()->iterator() as $value) {
echo "\n\tValue of current element of Map: ", $value->eventId
, ", " , $value->matchName, ", ", $value->tournament
, ", ", $value->results;
}
}
您将获得以下内容:
Key of current element of Map: Tour1
Value of current element of Map: 1234, match1, Tour1, 1-0
Value of current element of Map: 7890, match3, Tour1, 1-2
Key of current element of Map: Tour2
Value of current element of Map: 5678, match2, Tour2, 0-1
现在您只需要添加所需的HTML标记。
您可以使用以下功能访问mysql数据库:
mysqli_connect
mysqli_fetch_array
请参阅以下链接的示例#2:
Get results from mysql database
最终的代码可能是这样的:
$link = mysqli_connect ("my_host", "my_user", "my_password", "my_database");
$results = mysqli_query ($link, "select * from events order by Tournament");
$currentTournament = "";
while ($row = mysqli_fetch_array ($results, MYSQLI_ASSOC)) {
if (strcmp ($currentTournament, $row["Tournament"]) != 0) {
$currentTournament = $row["Tournament"];
echo "\n<thead><th>".$currentTournament."</th></thead>";
}
echo "\n<tr><td>".$row["EventID"]."</td><td>"
.$row["MatchName"]."</td><td>"
.$row["Tournament"]."</td><td>"
.$row["Results"]."</td></tr>";
}