Created
March 4, 2017 00:25
-
-
Save MarcosBL/ded03ece7a49b440d2e3b2c30c057ab8 to your computer and use it in GitHub Desktop.
Tabbed data from textarea conversion to array & nested html
This file contains 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
<?php | |
class Utils | |
{ | |
public static function tabs2array($list, $indentation = ' ') { | |
$result = array(); | |
$path = array(); | |
$list = str_replace("\r", "", $list); | |
foreach (explode("\n", $list) as $line) { | |
$depth = 0; | |
while (substr($line, 0, strlen($indentation)) === $indentation) { | |
$depth += 1; | |
$line = substr($line, strlen($indentation)); | |
} | |
while ($depth < sizeof($path)) { | |
array_pop($path); | |
} | |
$path[$depth] = $line; | |
$parent =& $result; | |
foreach ($path as $depth => $key) { | |
if (!isset($parent[$key])) { | |
$parent[$line] = array(); | |
break; | |
} | |
$parent =& $parent[$key]; | |
} | |
} | |
return Utils::array2html($result); | |
} | |
public static function array2html(Array $array = array(), $tag ="ol", $first_level = true) | |
{ | |
/* https://jsfiddle.net/MarcosBL/b3bzzk1y/ */ | |
$buffer = '<'.$tag.'>'; | |
foreach ($array as $key => $value) { | |
$buffer .= '<li>' . trim( $first_level ? "<strong>".$key."</strong>" : $key); | |
if (is_array($value)) { | |
$buffer .= Utils::array2html($value, $tag, false); | |
} | |
$buffer .= '</li>'; | |
} | |
$buffer .= '</'.$tag.'>'; | |
return $buffer; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I see something weird here. From a function called "tabs2array" I'd expect it returns an array... ;)
Thanks for sharing 👍