Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save pvankouteren/a9493cf49bda56cb90b81045fb6e22bd to your computer and use it in GitHub Desktop.

Select an option

Save pvankouteren/a9493cf49bda56cb90b81045fb6e22bd to your computer and use it in GitHub Desktop.
<?php
class ArrayFunctions {
public static function toString($array){
$result = array();
$depth = 0;
foreach($array as $k => $v) {
$show_val = ( is_array($v) ? "" : $v );
// show the indents
$result []= str_repeat(" ", $depth);
if($depth == 0) {
// this is a root node. no parents
$result []= "O ";
} elseif(is_array($v)) {
// this is a normal node. parents and children
$result []= "+ ";
} else {
// this is a leaf node. no children
$result []= "- ";
}
// show the actual node
if ($show_val == "") {
$result []= "<strong>{$k}</strong>:
";
}
else {
$result []= $k . " (".$show_val.")"."
";
}
if(is_array($v)) {
// this is what makes it recursive, rerun for childs
$temp = self::toTree($v, ($depth+1));
foreach($temp as $t) {
$result []= $t;
}
}
}
return implode($result);
}
private static function showtype($show_val) {
// convert bools to text and quote 'text bools'!
if (is_string($show_val) &&
($show_val == "true" || $show_val == "false")) {
return "\"{$show_val}\"";
}
elseif (is_bool($show_val) && $show_val === true) {
return "true";
}
elseif (is_bool($show_val) && $show_val === false) {
return "false";
}
elseif (is_null($show_val)) {
return "null";
}
else {
return $show_val;
}
}
private static function toTree($pieces, $depth = 0) {
foreach($pieces as $k => $v) {
// skip the baseval thingy. Not a real node.
//if($k == "__base_val") continue;
// determine the real value of this node.
$show_val = ( is_array($v) ? "" : $v );
$show_val = self::showtype($show_val);
// show the indents
$result []= str_repeat(" ", $depth);
if($depth == 0) {
// this is a root node. no parents
$result []= "O ";
} elseif(is_array($v)) {
// this is a normal node. parents and children
$result []= "+ ";
} else {
// this is a leaf node. no children
$result []= "- ";
}
// show the actual node
if ($show_val == "") {
$result []= "<strong>{$k}</strong>:
";
}
else {
$result []= $k . ": <i>{$show_val}</i>
";
}
if(is_array($v)) {
// this is what makes it recursive, rerun for childs
$temp = self::toTree($v, ($depth+1));
if (is_array($temp)) {
foreach($temp as $t) {
$result []= $t;
}
}
else {
$result []= $t;
}
}
}
return $result;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment