Loading index.php +30 −18 Original line number Diff line number Diff line Loading @@ -2,8 +2,9 @@ require_once __DIR__ . '/vendor/autoload.php'; $func = new Hp\Test\Functions(); use Hp\Test\Functions; $func = new Functions(); ?> <!DOCTYPE html> Loading Loading @@ -37,6 +38,7 @@ $func = new Hp\Test\Functions(); print_r($func->search($array, 54)); ?> <h1>Function 3</h1> <?php $arr = [ Loading @@ -48,6 +50,7 @@ $func = new Hp\Test\Functions(); print_r($func->uniqElements($arr)); ?> <h1>Function 4</h1> <?php $aMenu = [ Loading @@ -71,15 +74,24 @@ $func = new Hp\Test\Functions(); <h1>Function 5</h1> <?php print("<h2>До НГ: </h2>"); print($func->howDaysToNy(new DateTimeImmutable())); print "<h2>До НГ: </h2>"; try { print $func->howDaysToNy(new DateTimeImmutable()); } catch (Exception $e) { print $e->getMessage(); } ?> <h1>Function 6</h1> <?php print("<h2>Пятницы 13: </h2>"); print "<h2>Пятницы 13: </h2>"; try { foreach ($func->countFriday13(2024) as $date) { print($date->format("Y-m-d l") . "\n"); print $date->format("Y-m-d l") . "\n"; } } catch (Exception $e) { print $e->getMessage(); } ?> </body> Loading public/text.txtdeleted 100644 → 0 +0 −2 Original line number Diff line number Diff line Раз, два, три, четыре, Пять, шесть, семь, восемь. No newline at end of file src/Functions.php +130 −97 Original line number Diff line number Diff line <?php declare(strict_types=1); namespace Hp\Test; use DateTimeImmutable; use DateTime; use DateInterval; use DatePeriod; use Exception; class Functions { class Functions { /** * Выполняет сортировку массива по убыванию цены * * @param array $array * * Выполняет сортировку массива по убыванию цены * @param array $array * @return array */ function sortPrice(array $array): array { array_multisort(array_column($array, 'price'), SORT_DESC, array_column($array, 'count'), SORT_ASC, $array); public function sortPrice(array $array): array { $prices = array_column($array, 'price'); $counts = array_column($array, 'count'); array_multisort( $prices, SORT_DESC, $counts, SORT_ASC, $array ); return $array; } //На выход должна вернуть отсортированный массив по ключу *price* DESC и во вторую очередь по *count* ASC: //[ ['price'=>12, 'count'=>4], ['price'=>10, 'count'=>2], ['price'=>8, 'count'=>4], ['price'=>8, 'count'=>5], ['price'=>5, 'count'=>5], ] /** * На выход должна вернуть отсортированный массив по ключу *price* DESC * и во вторую очередь по *count* ASC: * [['price'=>12, 'count'=>4], ['price'=>10, 'count'=>2], ['price'=>8, 'count'=>4], * ['price'=>8, 'count'=>5], ['price'=>5, 'count'=>5],] */ /* Найдет элемент с указаным id * * @param array $array - массив, содержащий элементы со структурой * [ * 'id' => 30, * 'name' => 'Jhon', * 'age' => 23, * ] * @param $id - ид искомого элемента * * @return array - найденный элемент /** * Найдет элемент с указаным id * @param array $array - массив, содержащий элементы со структурой * [ * 'id' => 30, * 'name' => 'Jhon', * 'age' => 23, * ] * @param $id - ид искомого элемента * @return ?array - найденный элемент */ function search($array, $id): ?array { $rowId = array_search($id, array_column($array, 'id')); public function search(array $array, int $id): ?array { $rowId = array_search($id, array_column($array, 'id'), true); if ($rowId) { return $array[$rowId]; } return null; } /** * Удалить дубликаты, оставив только уникальные значения Loading @@ -45,12 +65,14 @@ class Functions { * @return array */ function uniqElements(array $array): array { public function uniqElements(array $array): array { return array_unique($array, SORT_REGULAR); } //Выходной массив: /** Array ( /** * Выходной массив: * Array ( * [0] => Array([0] => laravel, [1] => php) * [1] => Array([0] => codeigniter, [1] => php) * [3] => Array([0] => c++, [1] => java)) Loading @@ -59,16 +81,17 @@ class Functions { /** * Сгруппировать подразедлы в верхние разделы меню * Дочерние элементы поместить в массив родителя с ключом submenu * * Значение под ключом depth определяет уровень раздела * * Дочерние элементы поместить в массив родителя с ключом submenu * Значение под ключом depth определяет уровень раздела * Массив $aMenu всегда начинается с элемента depth = 0, * все последующие элементы с depth = 1 являются его дочерними * * элементами * * * @param array $aMenu * * * все последующие элементы с depth = 1 являются его дочерними * элементами * @param array $aMenu * @return array */ function prepareMenu(array $aMenu): array { public function prepareMenu(array $aMenu): array { $result = []; foreach ($aMenu as $arr) { if ($arr['depth'] === 0) { Loading @@ -87,7 +110,8 @@ class Functions { return $result; } /** Выходные данные: /** * Выходные данные: * $aMenu = [ * [ * 'name' => 'Смартфоны и гаджеты', Loading @@ -95,9 +119,8 @@ class Functions { * 'submenu' => [ * ['name' => 'Смартфоны, мобильные телефоны','depth' => 1,], * ['name' => 'Планшеты','depth' => 1,], * ['name' => 'Наушники и гарнитуры','depth' => 1,] * ,] * ,], * ['name' => 'Наушники и гарнитуры','depth' => 1,],], * ], * [ * 'name' => 'Компьютеры и ноутбуки', * 'depth' => 0, Loading @@ -111,35 +134,45 @@ class Functions { * 'submenu' => [ * ['name' => 'Техника для уборки','depth' => 1,], * ['name' => 'Товары для ухода за одеждой','depth' => 1,], * ['name' => 'Аксессуары для техники','depth' => 1,],]], * ['name' => 'Аксессуары для техники','depth' => 1,],] * ], * [ * 'name' => 'Товары для дома и кухни','depth' => 0, * 'name' => 'Товары для дома и кухни', * 'depth' => 0, * 'submenu' => [ * ['name' => 'Посуда','depth' => 1,],]], ]; * ['name' => 'Посуда','depth' => 1,],]], * ]; */ /** * Функция рассчитывает кол-во дней до нового года * @param DateTime $date дата от которой, необходимо рассчитать кол-во дней * @param DateTimeImmutable $date дата от которой, необходимо рассчитать кол-во дней * @return int * @throws Exception */ function howDaysToNy(DateTimeImmutable $date): int { public function howDaysToNy(DateTimeImmutable $date): int { $endYear = date("Y-12-31", date_timestamp_get($date)); $dateInterval = date_diff(new DateTimeImmutable($endYear), $date); return $dateInterval->format("%a") + 1; return (int)$dateInterval->format("%a") + 1; } /** * Вернет все пятницы 13 в году * @param int $yaer год, в котором необходимо произвести расчет * @param int $year год, в котором необходимо произвести расчет * @return DateTimeImmutable[] * @throws Exception */ function countFriday13(int $year): iterable { $stardDate = new DateTime("{$year}-01-01 Friday"); $year += 1; $endDate = new DateTime("{$year}-01-01"); public function countFriday13(int $year): iterable { $startDate = new DateTime("$year-01-01 Friday"); ++$year; $endDate = new DateTime("$year-01-01"); $interval = new DateInterval('P7D'); foreach(new DatePeriod($stardDate, $interval, $endDate) as $day) { foreach (new DatePeriod($startDate, $interval, $endDate) as $day) { yield new DateTimeImmutable($day->format("Y-m-d")); } } Loading Loading
index.php +30 −18 Original line number Diff line number Diff line Loading @@ -2,8 +2,9 @@ require_once __DIR__ . '/vendor/autoload.php'; $func = new Hp\Test\Functions(); use Hp\Test\Functions; $func = new Functions(); ?> <!DOCTYPE html> Loading Loading @@ -37,6 +38,7 @@ $func = new Hp\Test\Functions(); print_r($func->search($array, 54)); ?> <h1>Function 3</h1> <?php $arr = [ Loading @@ -48,6 +50,7 @@ $func = new Hp\Test\Functions(); print_r($func->uniqElements($arr)); ?> <h1>Function 4</h1> <?php $aMenu = [ Loading @@ -71,15 +74,24 @@ $func = new Hp\Test\Functions(); <h1>Function 5</h1> <?php print("<h2>До НГ: </h2>"); print($func->howDaysToNy(new DateTimeImmutable())); print "<h2>До НГ: </h2>"; try { print $func->howDaysToNy(new DateTimeImmutable()); } catch (Exception $e) { print $e->getMessage(); } ?> <h1>Function 6</h1> <?php print("<h2>Пятницы 13: </h2>"); print "<h2>Пятницы 13: </h2>"; try { foreach ($func->countFriday13(2024) as $date) { print($date->format("Y-m-d l") . "\n"); print $date->format("Y-m-d l") . "\n"; } } catch (Exception $e) { print $e->getMessage(); } ?> </body> Loading
public/text.txtdeleted 100644 → 0 +0 −2 Original line number Diff line number Diff line Раз, два, три, четыре, Пять, шесть, семь, восемь. No newline at end of file
src/Functions.php +130 −97 Original line number Diff line number Diff line <?php declare(strict_types=1); namespace Hp\Test; use DateTimeImmutable; use DateTime; use DateInterval; use DatePeriod; use Exception; class Functions { class Functions { /** * Выполняет сортировку массива по убыванию цены * * @param array $array * * Выполняет сортировку массива по убыванию цены * @param array $array * @return array */ function sortPrice(array $array): array { array_multisort(array_column($array, 'price'), SORT_DESC, array_column($array, 'count'), SORT_ASC, $array); public function sortPrice(array $array): array { $prices = array_column($array, 'price'); $counts = array_column($array, 'count'); array_multisort( $prices, SORT_DESC, $counts, SORT_ASC, $array ); return $array; } //На выход должна вернуть отсортированный массив по ключу *price* DESC и во вторую очередь по *count* ASC: //[ ['price'=>12, 'count'=>4], ['price'=>10, 'count'=>2], ['price'=>8, 'count'=>4], ['price'=>8, 'count'=>5], ['price'=>5, 'count'=>5], ] /** * На выход должна вернуть отсортированный массив по ключу *price* DESC * и во вторую очередь по *count* ASC: * [['price'=>12, 'count'=>4], ['price'=>10, 'count'=>2], ['price'=>8, 'count'=>4], * ['price'=>8, 'count'=>5], ['price'=>5, 'count'=>5],] */ /* Найдет элемент с указаным id * * @param array $array - массив, содержащий элементы со структурой * [ * 'id' => 30, * 'name' => 'Jhon', * 'age' => 23, * ] * @param $id - ид искомого элемента * * @return array - найденный элемент /** * Найдет элемент с указаным id * @param array $array - массив, содержащий элементы со структурой * [ * 'id' => 30, * 'name' => 'Jhon', * 'age' => 23, * ] * @param $id - ид искомого элемента * @return ?array - найденный элемент */ function search($array, $id): ?array { $rowId = array_search($id, array_column($array, 'id')); public function search(array $array, int $id): ?array { $rowId = array_search($id, array_column($array, 'id'), true); if ($rowId) { return $array[$rowId]; } return null; } /** * Удалить дубликаты, оставив только уникальные значения Loading @@ -45,12 +65,14 @@ class Functions { * @return array */ function uniqElements(array $array): array { public function uniqElements(array $array): array { return array_unique($array, SORT_REGULAR); } //Выходной массив: /** Array ( /** * Выходной массив: * Array ( * [0] => Array([0] => laravel, [1] => php) * [1] => Array([0] => codeigniter, [1] => php) * [3] => Array([0] => c++, [1] => java)) Loading @@ -59,16 +81,17 @@ class Functions { /** * Сгруппировать подразедлы в верхние разделы меню * Дочерние элементы поместить в массив родителя с ключом submenu * * Значение под ключом depth определяет уровень раздела * * Дочерние элементы поместить в массив родителя с ключом submenu * Значение под ключом depth определяет уровень раздела * Массив $aMenu всегда начинается с элемента depth = 0, * все последующие элементы с depth = 1 являются его дочерними * * элементами * * * @param array $aMenu * * * все последующие элементы с depth = 1 являются его дочерними * элементами * @param array $aMenu * @return array */ function prepareMenu(array $aMenu): array { public function prepareMenu(array $aMenu): array { $result = []; foreach ($aMenu as $arr) { if ($arr['depth'] === 0) { Loading @@ -87,7 +110,8 @@ class Functions { return $result; } /** Выходные данные: /** * Выходные данные: * $aMenu = [ * [ * 'name' => 'Смартфоны и гаджеты', Loading @@ -95,9 +119,8 @@ class Functions { * 'submenu' => [ * ['name' => 'Смартфоны, мобильные телефоны','depth' => 1,], * ['name' => 'Планшеты','depth' => 1,], * ['name' => 'Наушники и гарнитуры','depth' => 1,] * ,] * ,], * ['name' => 'Наушники и гарнитуры','depth' => 1,],], * ], * [ * 'name' => 'Компьютеры и ноутбуки', * 'depth' => 0, Loading @@ -111,35 +134,45 @@ class Functions { * 'submenu' => [ * ['name' => 'Техника для уборки','depth' => 1,], * ['name' => 'Товары для ухода за одеждой','depth' => 1,], * ['name' => 'Аксессуары для техники','depth' => 1,],]], * ['name' => 'Аксессуары для техники','depth' => 1,],] * ], * [ * 'name' => 'Товары для дома и кухни','depth' => 0, * 'name' => 'Товары для дома и кухни', * 'depth' => 0, * 'submenu' => [ * ['name' => 'Посуда','depth' => 1,],]], ]; * ['name' => 'Посуда','depth' => 1,],]], * ]; */ /** * Функция рассчитывает кол-во дней до нового года * @param DateTime $date дата от которой, необходимо рассчитать кол-во дней * @param DateTimeImmutable $date дата от которой, необходимо рассчитать кол-во дней * @return int * @throws Exception */ function howDaysToNy(DateTimeImmutable $date): int { public function howDaysToNy(DateTimeImmutable $date): int { $endYear = date("Y-12-31", date_timestamp_get($date)); $dateInterval = date_diff(new DateTimeImmutable($endYear), $date); return $dateInterval->format("%a") + 1; return (int)$dateInterval->format("%a") + 1; } /** * Вернет все пятницы 13 в году * @param int $yaer год, в котором необходимо произвести расчет * @param int $year год, в котором необходимо произвести расчет * @return DateTimeImmutable[] * @throws Exception */ function countFriday13(int $year): iterable { $stardDate = new DateTime("{$year}-01-01 Friday"); $year += 1; $endDate = new DateTime("{$year}-01-01"); public function countFriday13(int $year): iterable { $startDate = new DateTime("$year-01-01 Friday"); ++$year; $endDate = new DateTime("$year-01-01"); $interval = new DateInterval('P7D'); foreach(new DatePeriod($stardDate, $interval, $endDate) as $day) { foreach (new DatePeriod($startDate, $interval, $endDate) as $day) { yield new DateTimeImmutable($day->format("Y-m-d")); } } Loading