Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class selectOption
- {
- public $id;
- public $value;
- private $lvl;
- private $children;
- public function __construct($aLvl, $aId, $aValue)
- {
- $this->children = [];
- $this->lvl = $aLvl;
- $this->id = htmlspecialchars($aId);
- $this->value = htmlspecialchars($aValue);
- }
- /**
- * Zwraca ostatnie dziecko (jeśli nie istnieje, zwraca siebie)
- */
- public function lastChild()
- {
- if (isset($this->children))
- return $this->children[count($this->children) - 1];
- else
- return $this;
- }
- /**
- * Dodaje dziecko do tablicy
- * @param int $aId - Id dla tagu <option>
- * @param string $aValue - Zawartość tekstowa tagu <option>
- */
- public function pushChildren($aId, $aValue)
- {
- $this->children[] = new selectOption($this->lvl + 1, $aId, $aValue);
- }
- /**
- * Wyświetla kod swój i dzieci, jeśli jest to masteroption wyświetla same dzieci
- * @param &string $htmlCode - do tego stringa zostanie dopisany kod html
- */
- public function show(&$htmlCode)
- {
- if ($this->value != null) {
- $htmlCode .= '<option id="' . $this->id . '">' . str_repeat(' ', $this->lvl * 5) . $this->value . '</option>';
- //$htmlCode.='<option id="'.$this->id.'" style="padding-left: '.$this->lvl*(10).'px;">'.$this->value.'</option>';
- }
- foreach ($this->children as $child)
- {
- $child->show($htmlCode);
- }
- }
- }
- class tagSelect
- {
- private $masteroption;
- /**
- * Konstruktor; masteroption to główny obiekt typu selectOption, który ma przechowywać wszystkie dzieci.
- * Nie jest on widoczny, pełni tylko rolę kontenera
- * @param string $url - ścieżka do pliku z JSON
- */
- public function __construct($url)
- {
- $this->masteroption = new selectOption(-1, null, null);
- $this->generate($url);
- }
- public function getHtmlCode()
- {
- $htmlCode = '<select>';
- $this->masteroption->show($htmlCode);
- $htmlCode .= '</select>';
- return $htmlCode;
- }
- public function show()
- {
- echo $this->getHtmlCode();
- }
- /**
- * Rekurencyjna funkcja do interpretacji JSON
- * @param array $jsonChildren - tablica "childs" rodzica z kodu JSON
- * @param &selectOption $parentHandle - uchwyt do rodzica
- */
- private function parseOne($jsonChildren, &$parentHandle)
- {
- foreach ($jsonChildren as $v)
- {
- $parentHandle->pushChildren($v['id'], $v['name']);
- if (isset($v['childs']))
- $this->parseOne($v['childs'], $parentHandle->lastChild());
- }
- }
- /**
- * Pobiera zawartość JSON i zaczyna interpretację
- * @param string $url - ścieżka do pliku z JSON
- */
- private function generate($url)
- {
- if (!$json = file_get_contents($url))
- die('Can not open JSON file');
- $info = json_decode($json, true);
- if ($info == null)
- die('Bad JSON code');
- $this->parseOne($info, $this->masteroption);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement