Оптимизация вывода записи текущих боёв.

This commit is contained in:
Ivor Barhansky 2023-04-12 03:05:34 +03:00
parent 4e9d2deed4
commit 92318be837
2 changed files with 144 additions and 93 deletions

View File

@ -0,0 +1,71 @@
<?php
namespace Core;
class ArraySorter
{
/**
* Groups an array by a given key.
*
* Groups an array into arrays by a given key, or set of keys, shared between all array members.
*
* Based on {@author Jake Zatecky}'s {@link https://github.com/jakezatecky/array_group_by array_group_by()} function.
* This variant allows $key to be closures.
*
* @param array $array The array to have grouping performed on.
* @param mixed $key,... The key to group or split by. Can be a _string_,
* an _integer_, a _float_, or a _callable_.
*
* If the key is a callback, it must return
* a valid key from the array.
*
* If the key is _NULL_, the iterated element is skipped.
*
* ```
* string|int callback ( mixed $item )
* ```
*
* @return array|null Returns a multidimensional array or `null` if `$key` is invalid.
*/
public static function groupBy(array $array, $key): ?array
{
if (!is_string($key) && !is_int($key) && !is_float($key) && !is_callable($key)) {
return null;
}
$func = (!is_string($key) && is_callable($key) ? $key : null);
$key2 = $key;
// Load the new array, splitting by the target key
$grouped = [];
foreach ($array as $value) {
$key = null;
if (is_callable($func)) {
$key = call_user_func($func, $value);
} elseif (is_object($value) && property_exists($value, $key2)) {
$key = $value->{$key2};
} elseif (isset($value[$key2])) {
$key = $value[$key2];
}
if ($key === null) {
continue;
}
$grouped[$key][] = $value;
}
// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (func_num_args() > 2) {
$args = func_get_args();
foreach ($grouped as $key => $value) {
$params = array_merge([$value], array_slice($args, 2, func_num_args()));
$grouped[$key] = call_user_func_array('array_group_by', $params);
}
}
return $grouped;
}
}

View File

@ -1,5 +1,6 @@
<?php
use Core\ArraySorter;
use Core\Config;
use Core\Db;
@ -52,11 +53,11 @@ class FightRequest
[$eff['oneType'], $eff['id2'], $uid, $eff['mname'], $eff['mdata']]
);
// Db::sql('
// insert into eff_users (overType, id_eff, uid, name, timeUse, data)
// select oneType, id2, ?, mname, unix_timestamp(), mdata from eff_main
// where id2 = ?',
// [$uid, $id]);
// Db::sql('
// insert into eff_users (overType, id_eff, uid, name, timeUse, data)
// select oneType, id2, ?, mname, unix_timestamp(), mdata from eff_main
// where id2 = ?',
// [$uid, $id]);
}
@ -99,7 +100,9 @@ class FightRequest
}
if ($pl['users_in'] > 1) {
//Начало турнира
Db::sql('update turnirs set time = unix_timestamp() + ?, status = 1 where id = ?', [$pl['time3'], $pl['id']]);
Db::sql(
'update turnirs set time = unix_timestamp() + ?, status = 1 where id = ?', [$pl['time3'], $pl['id']]
);
$usp = mysql_query(
'SELECT * FROM `users` WHERE `inTurnirnew` = "' . $pl['id'] . '" LIMIT ' . $pl['users_in']
@ -336,7 +339,9 @@ class FightRequest
if (!$zayavka['nobot']) { // Если нет запрета на ботов.
$getRealPlayersQuery = 'select * from stats left join users on stats.id = users.id where exp >= ? and exp < ? and bot = 0 order by btl_cof desc limit 50';
$getBotsQuery = 'select * from stats left join users on stats.id = users.id where bot = 2 and exp >= ? and exp < ?';
$botUsers = Db::getRows($getBotsQuery, [$levelToExp[$zayavka['min_lvl_1']], $levelToExp[$zayavka['max_lvl_1'] + 1]]);
$botUsers = Db::getRows(
$getBotsQuery, [$levelToExp[$zayavka['min_lvl_1']], $levelToExp[$zayavka['max_lvl_1'] + 1]]
);
}
if (empty($botUsers)) {
@ -403,7 +408,9 @@ class FightRequest
$tm2 = [];
$i = [];
$toChat = $toWhere = '';
$users = Db::getRows('select * from stats left join users on stats.id = users.id where zv = ?', [$zv['id']]);
$users = Db::getRows(
'select * from stats left join users on stats.id = users.id where zv = ?', [$zv['id']]
);
foreach ($users as $user) {
!empty(${'tm' . $user['team']}) ?: ${'tm' . $user['team']} = [];
!empty($i[$user['team']]) ?: $i[$user['team']] = 0;
@ -1018,8 +1025,8 @@ class FightRequest
/**
* Звуковой пинг в чат?
* @todo убрать колхоз с условиями когда станет ясно как оно работает.
* @return void
* @todo убрать колхоз с условиями когда станет ясно как оно работает.
*/
private function sendSysChatSound(string $to = '', int $room = 0)
{
@ -1514,7 +1521,9 @@ class FightRequest
$sa = 'а';
}
$cmsg->setText(' [login:' . $this->u->info['login'] . '] отозвал' . $sa . ' свой запрос на бой.');
$cmsg->setText(
' [login:' . $this->u->info['login'] . '] отозвал' . $sa . ' свой запрос на бой.'
);
$cmsg->setCity($uz['city']);
$cmsg->setTo($uz['login']);
$chat->sendMsg($cmsg);
@ -2092,8 +2101,8 @@ function MM_jumpMenu(targ,selObj,restore){ //v3.0
<BR>
<BR>
<INPUT type="checkbox" name="travma">
Бой без правил <font color="#777">(проигравшая сторона получает инвалидность)</font><BR>
<INPUT type="checkbox" name="noatack"> Закрытый поединок <font color="#777">(бой будет изолирован от нападений)</font><BR>
Бой без правил <span style="color: #777; ">(проигравшая сторона получает инвалидность)</span><BR>
<INPUT type="checkbox" name="noatack"> Закрытый поединок <span style="color: #777; ">(бой будет изолирован от нападений)</span><BR>
<INPUT type="checkbox" name="noeff">
Запрет на использование свитков восстановления НР и Маны<BR>
';
@ -2110,87 +2119,54 @@ function MM_jumpMenu(targ,selObj,restore){ //v3.0
}
}
} elseif ($r == 6) {
//текущие
$x = 1;
$html = '';
$p = 0;
$_GET['from'] = round((int)$_GET['from']);
if ($_GET['from'] > 1 && $_GET['from'] < 50) {
$p = $_GET['from'] - 1;
}
$xx = mysql_num_rows(
mysql_query(
'SELECT `id` FROM `battle` WHERE `type` != 329 AND `team_win` = "-1" AND `time_over` = "0" AND `start1` > 0'
)
);
$px = $p * 15;
if ($p > ceil($xx / 15)) {
$p = ceil($xx / 15);
}
$sp = mysql_query(
'SELECT * FROM `battle` WHERE `type` != 329 AND `team_win` = "-1" AND `time_over` = "0" AND `start1` > 0 ORDER BY `time_start` DESC LIMIT ' . ((int)$px) . ',15'
);
while ($pl = mysql_fetch_array($sp)) {
$tm = '';
$tmu = [];
$tms = [];
$spi = mysql_query(
'SELECT `u`.`login`,`st`.`id`,`st`.`team`,`u`.`id` FROM `users` AS `u` LEFT JOIN `stats` AS `st` ON (`u`.`id` = `st`.`id`) WHERE `u`.`battle` = "' . $pl['id'] . '"'
);
while ($pli = mysql_fetch_array($spi)) {
if (!isset($tmu[$pli['team']])) {
$tms[count($tms)] = $pli['team'];
}
$tmu[$pli['team']][count($tmu[$pli['team']])] = $pli['id'];
}
$i = 0;
while ($i < count($tms)) {
$tmsu = '';
$j = 0;
while ($j < count($tmu[$tms[$j]])) {
if ($tmu[$tms[$i]][$j] > 0) {
$tmsu .= $this->u->microLogin($tmu[$tms[$i]][$j], 1) . ', ';
}
$j++;
}
$tmsu = rtrim($tmsu, ', ');
$tm .= $tmsu;
if ($i + 1 != count($tms)) {
$tm .= ' <SPAN style=\'color: red; font-weight: bold;\'>против</SPAN> ';
}
$i++;
}
if ($tm != '') {
$html .= ($p + $x) . '. <font class=date>' . date(
'd.m.y H:i', $pl['time_start']
) . '</font> ' . $tm . ' <IMG SRC="//img.new-combats.tech/i/fighttype' . $pl['typeBattle'] . '.gif" WIDTH=20 HEIGHT=20 ALT="Физический бой"> <A HREF="logs.php?log=' . $pl['id'] . '&rnd=' . $code . '" target=_blank>»»</A><BR>';
}
$x++;
}
?>
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td valign="top" align="center"><h3>Записи текущих боев на <?= date('d.m.Y'); ?>
(всего <?= $xx; ?>)</h3></td>
<td valign="top" align="right"></td>
</tr>
</table>
<?php if ($html == '') {
echo '<div align="center">К сожалению сейчас боев нет...</div>';
} else {
echo '<div>' . $html . '</div>';
} ?>
<TABLE width=100% cellspacing=0 cellpadding=0>
<TR>
<TD align=left><?php if ($p > 0 && $xx > 15) { ?><A HREF="?zayvka=1&r=6&from=<?= ($p - 1); ?>">««
предыдущая страница</A><?php } ?>&nbsp;
</TD>
<TD align=right><?php if ($p * 15 - $xx > 0) { ?><A HREF="?zayvka=1&r=6&from=<?= ($p + 1); ?>">
следующая страница »»</A><?php } ?>&nbsp;
</TD>
</TR>
</TABLE>
<h3>Записи текущих боев на <?= date('d.m.Y'); ?></h3>
<?php
///new
$query = 'select login, users.id, team, battle, time_start, typeBattle from users left join stats on users.id = stats.id left join battle on users.battle = battle.id where battle in (select id from battle where type != 329 and team_win = -1 and time_over = 0 and start1 > 0 order by time_start) order by battle desc';
$currentBattles = Db::getRows($query);
if (empty($currentBattles)) {
echo '<div style="text-align: center;">К сожалению сейчас боев нет...</div>';
} else {
// Надеялся на вывод вида:
// [battle -> [team -> [uid, uid, uid], team -> [uid, uid, uid],]],
// [battle -> [team -> [uid, uid, uid], team -> [uid, uid, uid],]],
// но глубоко наломался, где-то перемудрил с ArraySorter::groupBy()
// и на выходе там сортировка, но с сохранением всех вложенностей,
// что усложнило последющий вывод. Но вышло как вышло. Ins.
$currentBattlesArray = ArraySorter::groupBy($currentBattles, 'battle');
echo '<ol>';
foreach ($currentBattlesArray as $battleId => $cb) {
$players = '';
$typeBattle = 0;
$timeStart = 0;
$teams = ArraySorter::groupBy($cb, 'team');
foreach ($teams as $teamId => $team) {
foreach ($team as $key => $player) {
$players .= $this->u->microLogin($player['id']);
if ($key !== array_key_last($team)) {
$players .= ', ';
} else {
$typeBattle = $player['typeBattle'];
$timeStart = $player['time_start'];
}
}
if ($teamId === array_key_first($teams)) {
$players .= '<strong style="color: red;"> против </strong>';
}
}
echo '<li><span class=date>' . date('d.m.y H:i', $timeStart) . '</span>';
echo " $players ";
echo '<img src="//' . Config::get('img') . '/i/fighttype' . $typeBattle . '.gif" alt="">';
echo '<a href="//' . Config::get('host') . '/logs.php?log=' . $battleId .
'&rnd=' . $code . '">▶▶</a>';
}
echo '</ol>';
}
///new
} elseif ($r == 7) {
//завершенные
$btl = '';
@ -2663,7 +2639,9 @@ function MM_jumpMenu(targ,selObj,restore){ //v3.0
)
);
$d1 = '';
if ($uz['id'] == $this->u->info['id'] || $uze['id'] == $this->u->info['id'] || $this->u->info['level'] <= Config::get('bot_level')) {
if ($uz['id'] == $this->u->info['id'] || $uze['id'] == $this->u->info['id'] || $this->u->info['level'] <= Config::get(
'bot_level'
)) {
$d1 = 'disabled="disabled"';
}
if (!isset($uze['id']) || $this->u->info['zv'] == $pl['id']) {
@ -2813,7 +2791,9 @@ function MM_jumpMenu(targ,selObj,restore){ //v3.0
}
$cmsg = new ChatMessage();
$cmsg->setText(' [login:' . $this->u->info['login'] . '] принял' . $sa . ' вашу заявку на бой.[reflesh_main_zv_priem:' . $this->u->info['id'] . ']');
$cmsg->setText(
' [login:' . $this->u->info['login'] . '] принял' . $sa . ' вашу заявку на бой.[reflesh_main_zv_priem:' . $this->u->info['id'] . ']'
);
$cmsg->setCity($uz1['city']);
$cmsg->setTo($uz1['login']);
$cmsg->setType(6);