Загрузка данных
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Моделирование работы маркетплейса (PHP)</title>
<style>
table { border-collapse: collapse; width: 100%; margin-top: 20px; }
th, td { border: 1px solid #333; padding: 8px; text-align: left; }
th { background-color: #eee; }
.controls { margin-bottom: 20px; padding: 10px; border: 1px solid #ccc; }
</style>
</head>
<body>
<?php
// =========================================================
// 1. ФУНКЦИИ ГЕНЕРАЦИИ (Аналоги JS-функций)
// =========================================================
function generateName() {
$alphabetLower = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
$alphabetUpper = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ';
$digits = '0123456789';
$name = $alphabetUpper[rand(0, mb_strlen($alphabetUpper) - 1)];
$length = rand(5, 7);
for ($i = 1; $i < $length; $i++) {
if (rand(0, 1) > 0.5) {
$name .= $alphabetLower[rand(0, mb_strlen($alphabetLower) - 1)];
} else {
$name .= $digits[rand(0, strlen($digits) - 1)];
}
}
return $name;
}
function generateDescription() {
$words = ['крутой', 'удобный', 'стильный', 'качественный', 'дешевый', 'надежный', 'современный', 'быстрый', 'легкий', 'мощный', 'компактный'];
$description = '';
$wordCount = rand(5, 7);
for ($i = 0; $i < $wordCount; $i++) {
$description .= $words[rand(0, count($words) - 1)] . ' ';
}
return trim($description);
}
// =========================================================
// 2. ОБРАБОТКА ДАННЫХ И ГЕНЕРАЦИЯ МАССИВА
// =========================================================
$count = isset($_GET['count']) ? (int)$_GET['count'] : 10;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'none';
if ($count < 1) $count = 1;
if ($count > 50) $count = 50;
$brands = ['Samsung', 'Apple', 'Xiaomi', 'Huawei', 'Sony', 'LG', 'Asus'];
$products = array();
for ($i = 0; $i < $count; $i++) {
$products[] = array(
"Название" => generateName(),
"Цена" => rand(100, 10100),
"Количество" => rand(1, 50),
"Описание" => generateDescription(),
"Бренд" => $brands[rand(0, count($brands) - 1)]
);
}
// Сортировка
if ($sort === 'name') {
usort($products, function($a, $b) { return strcmp($a['Название'], $b['Название']); });
} elseif ($sort === 'quantity') {
usort($products, function($a, $b) { return $a['Количество'] - $b['Количество']; });
} elseif ($sort === 'price') {
usort($products, function($a, $b) { return $a['Цена'] - $b['Цена']; });
}
?>
<h1>Список товаров</h1>
<div class="controls">
<form method="GET">
<label>Сколько товаров вывести?
<input type="number" name="count" value="<?= $count ?>" min="1" max="50">
</label>
<button type="submit">Получить товары</button>
<br><br>
<label>Сортировка (список):
<select name="sort" onchange="this.form.submit()">
<option value="none" <?= $sort == 'none' ? 'selected' : '' ?>>Без сортировки</option>
<option value="name" <?= $sort == 'name' ? 'selected' : '' ?>>По названию</option>
<option value="quantity" <?= $sort == 'quantity' ? 'selected' : '' ?>>По количеству</option>
</select>
</label>
<button type="submit" name="sort" value="name">Сортировать по названию</button>
<button type="submit" name="sort" value="price">Сортировать по цене</button>
<button type="submit" name="sort" value="quantity">Сортировать по кол-ву</button>
</form>
</div>
<!-- ========================================================= -->
<!-- ТАБЛИЦА 1: Исходные данные -->
<!-- ========================================================= -->
<h2>Таблица 1. Исходные данные</h2>
<table>
<thead>
<tr>
<th>Название</th>
<th>Цена</th>
<th>Кол-во</th>
<th>Описание</th>
<th>Бренд</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?= $product['Название'] ?></td>
<td><?= $product['Цена'] ?> ₽</td>
<td><?= $product['Количество'] ?> шт.</td>
<td><?= $product['Описание'] ?></td>
<td><?= $product['Бренд'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php
// =========================================================
// 3. ЛОГИКА ПОКУПКИ (Добавлено из задачи про цветы)
// =========================================================
// Случайно выбираем товар и количество для покупки (от 0 до 30)
$random_index = array_rand($products);
$random_product_name = $products[$random_index]['Название'];
$buy_quantity = rand(0, 30);
echo "<h3>Случайная покупка:</h3>";
echo "<p>Выбран товар: <b>$random_product_name</b> в количестве: <b>$buy_quantity</b> шт.</p>";
// Ищем этот товар в массиве и меняем его количество
foreach ($products as $key => $product) {
if ($product['Название'] == $random_product_name) {
$current_stock = $product['Количество'];
$remainder = $current_stock - $buy_quantity;
// Логика:
// Если запрашивают больше, чем есть (remainder < 0), покупка отменяется.
// Если хватает или ровно столько — записываем остаток (включая 0).
if ($remainder < 0) {
$products[$key]['Количество'] = $current_stock;
} else {
$products[$key]['Количество'] = $remainder;
}
break;
}
}
?>
<!-- ========================================================= -->
<!-- ТАБЛИЦА 2: Остаток после покупки -->
<!-- ========================================================= -->
<h2>Таблица 2. Остаток после попытки покупки</h2>
<table>
<thead>
<tr>
<th>Название</th>
<th>Цена</th>
<th>Кол-во</th>
<th>Описание</th>
<th>Бренд</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?= $product['Название'] ?></td>
<td><?= $product['Цена'] ?> ₽</td>
<td><?= $product['Количество'] ?> шт.</td>
<td><?= $product['Описание'] ?></td>
<td><?= $product['Бренд'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>