[ create a new paste ] login | about

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

PHP, pasted on Oct 25:
<?php

// Mmmm... functiony goodness
function array_to_toc ($in, &$out, $level = '') {
  foreach ($in as $key => $item) { // Loop items
    $thisLevel = ($level) ? "$level.".($key + 1) : ($key + 1); // Get this level as string
    $out[$thisLevel] = $item['name']; // Add this item to $out
    if (isset($item['subs']) && is_array($item['subs']) && count($item['subs'])) array_to_toc($item['subs'],$out,$thisLevel); // Recurse children of this item
  }
}

// Here is your test data (slightly modified - I think you stated it wrong in the question)
$array = array (
  0 => array (
    'name' => 'test1',
    'subs' => array (
      0 => array (
        'name' => 'test2'
      ),
      1 => array (
        'name' => 'test3',
        'subs' => array (
          0 => array (
            'name' => 'test4'
          )
        )
      )
    )
  ),
  1 => array (
    'name' => 'test5'
  )
);

// $result is passed by reference and will hold the output after the function has run
$result = array();
array_to_toc($array, $result);

print_r($result);

?>


Output:
1
2
3
4
5
6
7
8
Array
(
    [1] => test1
    [1.1] => test2
    [1.2] => test3
    [1.2.1] => test4
    [2] => test5
)


Create a new paste based on this one


Comments: