$myArray = [
1 => $array2
];
<?php
/* Функция для генерации купона */
function generateCoupon() {
return (object)[
'id' => uniqid(),
'code' => random_int(100000, 999999)
];
}
/* Для примера сохранять будем в сессию, а для этого первым делом убедимся что она запущена */
if (!session_id()) {
session_start();
}
/* Обрабатываем отправку пользователем формы - генерируем и сохраняем купон */
if ($_SERVER['REQUEST_METHOD'] === "POST") {
$_SESSION['coupon'] = generateCoupon();
/*
* После успешного сохранения перенаправляем пользователя на эту же страницу
* В данном конкретном примере у нас одна страница и без этого шага при обновлении страницы браузер предпримет попытку перепослать форму при обновлении страницы
* В более реальном коде сохранением будет заниматься отдельный обработчик и подобный код поможет вернуть пользователя обратно на страницу с формой/данными купона
*/
header("Location: {$_SERVER['REQUEST_URI']}");
die();
}
/* Вытаскиваем сохранённый купон, если таковой имеется */
$coupon = $_SESSION['coupon'] ?? null;
?>
<?php if (empty($coupon)) { ?>
<form method="POST">
<button>Сгенерировать купон</button>
</form>
<?php } else { ?>
<span>Ваш купон: "<b><?= $coupon->code ?>"</b> успешно добавлен, его ID = <?= $coupon->id ?>
<?php } ?>
function translit($value) {
$converter = [
'%D0%B0' => 'a',
'%D0%B1' => 'b',
'%D0%B2' => 'v',
'%D0%B3' => 'g',
'%D0%B4' => 'd',
'%D0%B5' => 'e',
'%D1%91' => 'e',
'%D0%B6' => 'zh',
'%D0%B7' => 'z',
'%D0%B8' => 'i',
'%D0%B9' => 'y',
'%D0%BA' => 'k',
'%D0%BB' => 'l',
'%D0%BC' => 'm',
'%D0%BD' => 'n',
'%D0%BE' => 'o',
'%D0%BF' => 'p',
'%D1%80' => 'r',
'%D1%81' => 's',
'%D1%82' => 't',
'%D1%83' => 'u',
'%D1%84' => 'f',
'%D1%85' => 'h',
'%D1%86' => 'c',
'%D1%87' => 'ch',
'%D1%88' => 'sh',
'%D1%89' => 'sch',
'%D1%8C' => '',
'%D1%8B' => 'y',
'%D1%8A' => '',
'%D1%8D' => 'e',
'%D1%8E' => 'yu',
'%D1%8F' => 'ya',
];
$decodedKeys = array_map(function($encodedKey) {
return urldecode($encodedKey);
}, array_keys($converter));
$converter = array_combine($decodedKeys, array_values($converter));
return strtr($value, $converter);
}
foreach ($items as $itemIndex=>$item) {
foreach($item['stocks'] as $stockIndex=>$stock) {
if ($stock['type'] === "fbo") {
unset($items[$itemIndex]['stocks'][$stockIndex]);
$items[$itemIndex]['stocks'] = array_values($items[$itemIndex]['stocks']);
}
}
}
function findPair(string $text, array $words, int $range=5) {
$rows = explode(PHP_EOL, $text);
$numberLength = 5;
$pair = null;
$isNumberFound = false;
foreach ($words as $word) {
foreach ($rows as $row) {
$wordPos = strpos($row, $word);
$isWordInRow = $wordPos !== false;
if (!$isWordInRow) {
continue;
}
/* Going backwards first */
$backwardSearchStart = $wordPos-1;
$backwardSearchEnd = $backwardSearchStart - $range;
for ($symbolPos=$backwardSearchStart; $symbolPos>$backwardSearchEnd; $symbolPos--) {
// Stop backward search if we are in the very beginning of the row
if ($symbolPos <= 0) {
break;
}
$symbol = substr($row, $symbolPos, 1);
if (is_numeric($symbol)) {
$lastNumberPos = $symbolPos - $numberLength;
$digits = [];
for ($digitPos=$symbolPos; $digitPos>$lastNumberPos; $digitPos--) {
$digit = substr($row, $digitPos, 1);
if (is_numeric($digit)) {
$digits[] = $digit;
} else {
break;
}
}
$isNumberFound = count($digits) === $numberLength;
if ($isNumberFound) {
$number = implode(array_reverse($digits));
$pair = [$word, $number];
break;
}
}
}
if ($isNumberFound) {
return $pair;
}
/* Forward search */
$forwardSearchStart = $wordPos+1+strlen($word);
$forwardSearchEnd = $forwardSearchStart + $range;
for ($symbolPos=$forwardSearchStart; $symbolPos<$forwardSearchEnd; $symbolPos++) {
$symbol = substr($row, $symbolPos, 1);
if (is_numeric($symbol)) {
$lastNumberPos = $symbolPos + $numberLength;
$digits = [];
for ($digitPos=$symbolPos; $digitPos<$lastNumberPos; $digitPos++) {
$digit = substr($row, $digitPos, 1);
if (is_numeric($digit)) {
$digits[] = $digit;
} else {
break;
}
}
$isNumberFound = count($digits) === $numberLength;
if ($isNumberFound) {
$number = implode($digits);
$pair = [$word, $number];
break;
}
}
}
if ($isNumberFound) {
return $pair;
}
}
}
return $pair;
}
$words = ["apple", "word", "new"];
$text = <<<TEXT
what, 10924
59012, test
VT 92918
word, 18913
site 85719
12345 Wisconsin
TEXT;
$pair = findPair($text, $words);
/* Result:
array(2) {
[0]=>
string(4) "word"
[1]=>
string(5) "18913"
}
*/
foreach ($secondArray as $secondArrayElement) {
$secondArrayElement = (array)$secondArrayElement; // вы везде пишете "массив", но, судя по вашему примеру, у вас тут объект, а не массив. Поэтому я сделал явное преобразование в массив на случай если была ошибка в формулировке.
$doesExistInFirstArray = false;
foreach ($firstArray as $firstArrayElement) {
if ($firstArrayElement['ID'] == $secondArrayElement['id']) {
$doesExistInFirstArray = true;
break;
}
}
$secondArrayElement['doesExistInFirstArray'] = $doesExistInFirstArray;
}
function render($part, array $vars=[]) {
extract($vars);
ob_start();
require __DIR__ . "/views/" . $part . ".php"; // путь тут поправь в соответствии с твоими реалиями
return ob_get_clean();
}
$user_html_entity = render("user_entity", compact(
"user_id",
"user_avatar_link",
"user_nickname",
"user_last_online_datetime",
"user_initials_info_string",
"user_location_string"
));
<a href="/user/<?= $user_id ?>" class="user" data-id="users___user_link">
<div class="section_900">
<img src="<?= $user_avatar_link ?>">
<div class="no_image_content">
<p class="nickname"><?= $user_nickname ?></p>
<p class="online_status"><?= Get_Online_Status_From_Datetime($user_last_online_datetime) ?></p>
<p class="initials"><?= $user_initials_info_string ?></p>
<p class="location"><?= $user_location_string ?></p>
</div>
</div>
</a>
function cleanText(string $text) {
$cleaned = [];
foreach (str_split($text) as $i=>$letter) {
if ($letter === "&" || $text[$i-1] === "&") {
continue;
}
$cleaned[] = $letter;
}
return implode("", $cleaned);
}
function justify(string $someWord, string $otherWord) {
$spaces = "";
if (strlen($someWord) !== strlen($otherWord)) {
$diff = abs(mb_strlen($someWord)-mb_strlen($otherWord));
$offset = ceil($diff/2);
$spaces = str_repeat(" ", $offset);
}
if (mb_strlen($someWord) >= mb_strlen($otherWord)) {
return $someWord . PHP_EOL . $spaces . $otherWord;
} else {
return $spaces . $someWord . PHP_EOL . $otherWord;
}
}
$checkUser = mysqli_query($connect, "SELECT * FROM `users` WHERE `email` == '$email' AND `password` == '$password'");
if ($checkUser === false) {
die(mysqli_error($connect));
}
// БЕЗОПАСНО выполняем запрос
$stmt = $link->prepare("SELECT * FROM comments WHERE art_id = ?");
$stmt->bind_param("s", $note_id);
$stmt->execute();
// получаем данные
$result = $stmt->get_result();
$comments = $result->fetch_all(MYSQLI_ASSOC);
<?php if ($comments): ?>
<?php foreach ($comments as $row): ?>
<?=$row['comment']?><br>
<?php endforeach ?>
<?php else: ?>
Эту запись еще никто не комментировал
<?php endif ?>
$queryString = http_build_query($params);
$decodedQueryString = urldecode($queryString); // Не совсем понимаю, зачем эта операция вообще. Объясните, зачем вы это делаете
$requestUrl = "https://oauth.vk.com/access_token?{$decodedQueryString}";
$response = file_get_contents($requestUrl);
$userInfo = json_decode($response);
$json = '{"status":{"timestamp":"2021-05-03T16:47:16.362Z","error_code":0,"error_message":null,"elapsed":370,"credit_count":0,"notice":null},"data":{"2016-10-26T02:39:28.000Z":{"BTC":[1],"USD":[660.28167725,87283944,10525640015.288086]},"2016-10-27T02:39:28.000Z":{"BTC":[1],"USD":[702.39459229,89816296,11200777509.550781]}}}';
$data = json_decode($json, true);
foreach($data['data'] as $date=>$values) {
$date = date("Y-m-d H:i:s", strtotime($date));
$usd = $values['USD'][0] ?? null;
$usd_two = $values['USD'][1] ?? null;
$usd_three = $values['USD'][2] ?? null;
// Далее здесь можно вызвать функцию, которая сохранит значения в базу
}
$fromDb = [
['id'=>1, 'day'=>2, 'month'=>1],
['id'=>2, 'day'=>22, 'month'=>3],
['id'=>2, 'day'=>31, 'month'=>2],
['id'=>4, 'day'=>12, 'month'=>2],
['id'=>5, 'day'=>4, 'month'=>3]
];
function groupBy(array $elements, callable $getUniqueKey) {
$grouped = [];
foreach ($elements as $element) {
$uniqueKey = $getUniqueKey($element);
$grouped[$uniqueKey][] = $element;
}
return $grouped;
}
$groupedByMonth = groupBy($fromDb, function($row) {
return $row['month'];
});