Created
December 19, 2016 14:49
-
-
Save MeGaPk/e14f04ec63949f7b6be9b195f0390e26 to your computer and use it in GitHub Desktop.
test task just for fun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Developed by Ivan Gaydamakin (vk.com/megapk) --> | |
<!-- License MIT --> | |
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Тег UL</title> | |
</head> | |
<body> | |
<?php | |
error_reporting(E_ALL); | |
ini_set('display_errors', 1); | |
class GeneratorCategories | |
{ | |
private $filename; | |
private $names; | |
public function __construct($filename) | |
{ | |
$this->names = []; | |
$this->filename = $filename; | |
} | |
public function GenerateHtmlCategories() | |
{ | |
$structure = $this->parseFileToStructure($this->filename); | |
$categories = $this->parseStructureToCategories($structure); | |
return $this->renderCategoriesToHtml($categories); | |
} | |
private function parseFileToStructure($filename) | |
{ | |
$structure = []; | |
foreach (file($filename) as $line) { | |
$line = trim($line); | |
if ($line == "") | |
continue; | |
list($id, $parent_id, $name) = explode("|", $line); | |
$this->names[$id] = $name; | |
$id = intval($id); | |
$parent_id = intval($parent_id); | |
if (empty($structure[$parent_id])) { | |
$structure[$parent_id] = []; | |
} | |
$structure[$parent_id][$id] = []; | |
} | |
ksort($structure); | |
return $structure; | |
} | |
private function fillParentCategory(array &$categories, $for_search_parent_id, $for_add_ids) | |
{ | |
foreach ($categories as $category_id => &$category) { | |
if ($category_id == $for_search_parent_id) { | |
$category = $category + $for_add_ids; | |
} else if (count($category) > 0) { | |
$this->fillParentCategory($category, $for_search_parent_id, $for_add_ids); | |
} | |
} | |
} | |
function renderCategoriesToHtml(array $categories, $depth = 0, &$html = "") | |
{ | |
foreach ($categories as $category_id => &$category) { | |
if ($category_id != 0) { | |
$html .= "<ul><li>"; | |
$html .= $this->names[$category_id]; | |
} | |
if (count($category)) { | |
$depth += 1; | |
$this->renderCategoriesToHtml($category, $depth, $html); | |
} | |
if ($category_id != 0) { | |
$html .= "</li></ul>"; | |
} | |
} | |
return $html; | |
} | |
private function parseStructureToCategories($structure) | |
{ | |
$categories = [0 => $structure[0]]; | |
unset($structure[0]); | |
foreach ($structure as $parent_id => $ids) { | |
$this->fillParentCategory($categories, $parent_id, $ids); | |
} | |
return $categories; | |
} | |
} | |
$generator = new GeneratorCategories("file.txt"); | |
echo $generator->GenerateHtmlCategories(); | |
?> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment