Advertisement
Guest User

Untitled

a guest
Nov 13th, 2013
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.40 KB | None | 0 0
  1. <?php
  2. $array = [
  3.   ['level'=>1, 'name' => 'Root #1'],
  4.   ['level'=>1, 'name' => 'Root #2'],
  5.   ['level'=>2, 'name' => 'subroot 2-1'],
  6.   ['level'=>3, 'name' => '__subroot 2-1/1'],
  7.   ['level'=>2, 'name' => 'subroot 2-2'],
  8.   ['level'=>1, 'name' => 'Root #3']
  9. ];
  10.  
  11. function benchmark(callable $function, $args = null, $count = 1) {
  12.    $time = microtime(true);
  13.    
  14.    for($i=0; $i<$count; $i++) {
  15.       $result = is_array($args)?
  16.                 call_user_func_array($function, $args):
  17.                 call_user_func_array($function);
  18.    }
  19.    
  20.    return [
  21.       'count' => $count,
  22.       'total'   => microtime(true) - $time,
  23.       'average' => (microtime(true) - $time) / $count
  24.    ];
  25. }
  26.  
  27. function generateParentIdentifiers(array $array) {
  28.     $length = count($array);
  29.    
  30.     for ($i = 0; $i < $length; $i++) {
  31.         $current = &$array[$i];
  32.         $current['parent'] = 0;
  33.        
  34.         for ($j = $i; $j >= 0; $j--) {
  35.             if ($current['level'] - $array[$j]['level'] === 1) {
  36.                 $current['parent'] = $j;
  37.                 break;
  38.             }
  39.         }
  40.     }
  41.    
  42.     return $array;
  43. }
  44.  
  45. function buildTree(array $array) {
  46.     $nodes = generateParentIdentifiers($array);
  47.     $tree = [];
  48.    
  49.     foreach ($nodes as &$node) {
  50.         $node['children'] = [];
  51.        
  52.         if ($node['parent'] !== 0) {
  53.             $nodes[$node['parent']]['children'][] = &$node;
  54.         } else {
  55.             $tree[] = &$node;
  56.         }
  57.     }
  58.    
  59.     return $tree;
  60. }
  61. echo '<pre>';
  62. var_dump(benchmark('buildTree', [$array], 1000000));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement