Skip to content

Instantly share code, notes, and snippets.

@MarcosBL
Created March 4, 2017 00:25
Show Gist options
  • Save MarcosBL/ded03ece7a49b440d2e3b2c30c057ab8 to your computer and use it in GitHub Desktop.
Save MarcosBL/ded03ece7a49b440d2e3b2c30c057ab8 to your computer and use it in GitHub Desktop.
Tabbed data from textarea conversion to array & nested html
<?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;
}
}
@skarcha
Copy link

skarcha commented Mar 4, 2017

I see something weird here. From a function called "tabs2array" I'd expect it returns an array... ;)

Thanks for sharing 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment