[ create a new paste ] login | about

Link: http://codepad.org/zgfHvkBV    [ raw code | output | fork ]

PHP, pasted on Jan 16:
<?php
$list =
'Home
Products
    Product 1
        Product 1 Images
    Product 2
        Product 2 Images
    Where to Buy
About Us
    Meet the Team
    Careers
Contact Us';

function helper($list, $indentation = '    ') {
  $result = array();
  $path = array();
  
  foreach (explode("\n", $list) as $line) {
    // get depth and label
    $depth = 0;
    while (substr($line, 0, strlen($indentation)) === $indentation) {
      $depth += 1;
      $line = substr($line, strlen($indentation));
    }
    
    // truncate path if needed
    while ($depth < sizeof($path)) {
      array_pop($path);
    }
    
    // keep label (at depth)
    $path[$depth] = trim($line);
    
    // traverse path and add label to result
    $parent =& $result;
    foreach ($path as $depth => $key) {
      if (!isset($parent[$key])) {
        $parent[$key] = array();
        break;
      }
      
      $parent =& $parent[$key];
    }
  }
  
  // return
  return $result;
}

print_r(helper($list));


Output:
Array
(
    [Home] => Array
        (
        )

    [Products] => Array
        (
            [Product 1] => Array
                (
                    [Product 1 Images] => Array
                        (
                        )

                )

            [Product 2] => Array
                (
                    [Product 2 Images] => Array
                        (
                        )

                )

            [Where to Buy] => Array
                (
                )

        )

    [About Us] => Array
        (
            [Meet the Team] => Array
                (
                )

            [Careers] => Array
                (
                )

        )

    [Contact Us] => Array
        (
        )

)


Create a new paste based on this one


Comments: