<?php
// расчет статистики с исключением повторов результатов по одному человеку/вопросу
class report_quiz_stats4 extends c_report
{
    var $title='Результаты контроля знаний - статистика' ;
    var $personal_id=0 ;
    var $event_id=0 ;
    var $cnt_days=array(0=>'30 дней',1=>'90 дней',2=>'180 дней',3=>'1 год',4=>'все время') ;
    var $usl_time ;
    var $time_from ;
    var $usl_quiz_result ;
    var $use_fusioncharts=1;
    var $usl_theme_select;
    var $view_as_question=0;



    function init($crete_options=array())
    {    $cnt_day=($this->filter['cnt_days'])? (int)$this->filter['cnt_days']:0;
        $tt=getdate() ;
        $this->time_from=0 ;
        $this->time_to = mktime(0,0,0,$tt['mon'],$tt['mday']+1,$tt['year']) - 1;

        switch($cnt_day)
        {
            case 0: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday']-29,$tt['year']);
                $this->usl_time='and t1.quiz_с_data>='.$this->time_from;
                break ;
            case 1: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday']-89,$tt['year']);
                $this->usl_time='and t1.quiz_с_data>='.$this->time_from;
                break ;
            case 2: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday']-179,$tt['year']);
                $this->usl_time='and t1.quiz_с_data>='.$this->time_from;
                break ;
            case 3: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday'],$tt['year']-1) ;
                $this->usl_time='and t1.quiz_с_data>='.$this->time_from;
                break ;
            case 4: $this->usl_time='' ;
                break ;
        }

        $_usl=array() ;
//        $_usl[]='not t3.parent is null' ;
        if ($this->personal_id)    $_usl[]='personal_id='.$this->personal_id ;
        if ($this->event_id)       $_usl[]='event_id='.$this->event_id ;

        $this->usl_theme_select=(_sizeof($_usl))? implode(' and ',$_usl):'1' ;

        if ($this->filter['theme_id'])
        {   $questions_ids=[] ; $section_ids=[];
            if (!$this->filter['section_id']) $section_ids=execSQL_line('select pkey as id from quiz_themes where parent2='.$this->filter['theme_id'].' ') ;
            else {
                $section_level=execSQL_value('select level from quiz_themes where pkey='.$this->filter['section_id']);
                if ($section_level) {
                    $section_ids=execSQL_line('select pkey as id from quiz_themes where parent'.$section_level.'='.$this->filter['section_id'].' ') ;
                    if (!_sizeof($section_ids)) $section_ids=[$this->filter['section_id']];
                }
            }
            if (_sizeof($section_ids))  {
                $questions_ids=execSQL_line('select pkey as id from quiz_questions where parent in ('.implode(',',$section_ids).')') ;
            } else {
                $questions_ids=execSQL_line('select pkey as id from quiz_questions where parent='.$this->filter['theme_id']) ;
            }
            if (_sizeof($questions_ids)) $_usl[]='question_id in ('.implode(',',$questions_ids).')';
            else $_usl[]='question_id=-1';
        }
        if (_sizeof($this->filter['org_ids']))    $_usl[]='_org_id in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
        if (_sizeof($this->filter['otdel_ids']))  $_usl[]='_otdel_id in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
        if (_sizeof($this->filter['working_ids']))  $_usl[]='working in ('.implode(',',array_keys($this->filter['working_ids'])).')' ;

        $this->usl_quiz_result=(_sizeof($_usl))? implode(' and ',$_usl):'1' ;

        //damp_array($_usl,1,-1);
    }

    function get_setting_arr()
    {
        list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;
        // получаем список всех ТЕМ вопросов, которые задавались сотруднику


        $parent_themes = execSQL('select t3.pkey,t3.parent,t3.parent2,t3.level,t3.obj_name 
                                    from quiz_result t1
                                        inner join quiz_questions t2 on t2.pkey=t1.question_id 
                                        inner join quiz_themes t3 on t3.pkey=t2.parent
                                        left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                                        where '.$this->usl_theme_select.' and not tp.pkey is null
                                        group by t3.pkey
                                        order by t3.pkey
        ');

        $themes=execSQL('select pkey,clss,obj_name,parent,level,parent2 from quiz_themes where level>0 order by level,parent');

        $themes=$this->hierarchy_array($themes);


        $max_level=0;
        foreach ($themes as $key=>&$theme) {
            if ($theme['level']>$max_level) $max_level=$theme['level'];
            if (_sizeof($parent_themes[$key])) { $theme['in_view']=true;}
        }

        if ($max_level>0) {
            for ($i=$max_level;$i>0;$i--) {
                foreach ($themes as $key=>$theme) {
                    if ($theme['level']!=$i) continue;
                    if (!$theme['in_view']) {
                        unset($themes[$key]);
                        continue;
                    }
                    if ($theme['parent']) {
                        $themes[$theme['parent']]['in_view']=true;
                    }
                    if ($theme['clss']==481) unset($themes[$key]);
                }
            }
        }

        $arr_themes=array() ; $arr_themes_section=array() ;

        foreach ($themes as $key=>$theme) {
            if ($theme['level']==2) {
                $arr_themes[$key]=$theme['obj_name'] ;
//                $arr_themes_section[$rec['theme_id']][$rec['section_id']]=$rec['section_name'] ;
            } elseif ($theme['level']>2) {
                $arr_themes_section[$theme['parent2']][$key]=$this->empty_space($theme['level']).$theme['obj_name'] ;
            }
        }

        return [$arr_orgs_ids,$arr_otdel_ids,$arr_themes,$arr_themes_section,$arr_works_ids];
    }

    function setting()
    {
        list($arr_orgs_ids,$arr_otdel_ids,$arr_themes,$arr_themes_section,$arr_workd_ids)=$this->get_setting_arr();

        $this->form_open() ;
        $this->fieldset_open() ;
        $this->row_open() ;
        $this->filter_section_select('theme_id','Тема КЗ:',2,$arr_themes) ;
//        if ($this->filter['theme_id']) $this->filter_section_select_multiple('section_ids','Разделы КЗ:',4,$arr_themes_section[$this->filter['theme_id']]) ;
            if ($this->filter['theme_id']) $this->filter_section_select('section_id','Раздел КЗ:',3,$arr_themes_section[$this->filter['theme_id']]) ;
            //$this->filter_section_select('view_mode','Обзор:',2,$this->view_mode,array('nospace_element'=>1)) ;
            $this->filter_section_select('cnt_days','Обзор за:',2,$this->cnt_days,array('nospace_element'=>1)) ;
        $this->row_close() ;
        $this->row_open() ;
        if (!$this->personal_id) $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
        if (!$this->personal_id) $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
            if (!$this->personal_id) $this->filter_section_select_multiple('working_ids','Должность:',4,$arr_workd_ids) ;
        $this->row_close() ;
        ?><div id="panel_buttons" class="apply_filter_panel"><input type="submit" class="button v2" cmd="set_filter" value="Применить"></div><?
        $this->fieldset_close() ;
        $this->form_close() ;
    }

    function setting_with_rating()
    {
        list($arr_orgs_ids,$arr_otdel_ids,$arr_themes,$arr_themes_section,$arr_workd_ids)=$this->get_setting_arr();

        $this->form_open() ;
        $this->fieldset_open() ;
        $this->row_open() ;
            $this->filter_section_select('theme_id','Тема КЗ:',2,$arr_themes) ;
            //        if ($this->filter['theme_id']) $this->filter_section_select_multiple('section_ids','Разделы КЗ:',4,$arr_themes_section[$this->filter['theme_id']]) ;
            if ($this->filter['theme_id']) $this->filter_section_select('section_id','Раздел КЗ:',3,$arr_themes_section[$this->filter['theme_id']]) ;
        //$this->filter_section_select('view_mode','Обзор:',2,$this->view_mode,array('nospace_element'=>1)) ;
            $this->filter_section_select('cnt_days','Обзор за:',2,$this->cnt_days,array('nospace_element'=>1)) ;
        $this->row_close() ;
        $this->row_open() ;
            if (!$this->personal_id) $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
            if (!$this->personal_id) $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
            if (!$this->personal_id) $this->filter_section_select_multiple('working_ids','Должность:',4,$arr_workd_ids) ;
        $this->row_close() ;
        $this->row_open() ;
            ?>
            <section class="col col-2">
                <label class="checkbox">
                    <input type="checkbox" name="filter[view_count]" value="1" <?if ($this->filter['view_count']) echo 'checked'?>><i></i>Отображать кол-во вопросов
                </label>
            </section>
            <?
        $this->row_close() ;
        ?><div id="panel_buttons" class="apply_filter_panel"><input type="submit" class="button v2" cmd="set_filter" value="Применить"></div><?
        $this->fieldset_close() ;
        $this->form_close() ;
    }

    function new_setting()
    {
        list($arr_orgs_ids,$arr_otdel_ids,$arr_themes,$arr_themes_section)=$this->get_setting_arr();

        $options=[];

        $col_count=2;
        $element_title='Тема КЗ';
        $element_name='theme_id';
        $cur_value=(isset($options['cur_value']))? $options['cur_value']:$this->filter[$element_name];
        $el_name=(strpos($element_name,'[')!==false)? $element_name:'filter['.$element_name.']' ;
        ?>
        <div id="panel_filter">
            <form class="sky-form test_form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
                <div class="row">
                    <section  class="<?if ($col_count) echo 'col col-'.$col_count?>">
                        <label class="select">
                            <select class="filter dropdown place_holder" name="<?echo $el_name?>" title="<?=$element_title?>">
                                    <option value="" disabled selected><?=$element_title?></option>
                                <?
                                if (_sizeof($arr_themes)) foreach($arr_themes as $id=>$value)
                                {
                                    $key=(is_array($value) and $options['key_fname'])?  $value[$options['key_fname']]:$id ;
                                    $val=(is_array($value))?  $value['obj_name']:$value ;
                                    ?><option value="<?echo $key?>" <?if($cur_value==$key) echo 'selected'?>><?echo $val?></option><?
                                }
                                ?>
                            </select><i></i>
                    </section>
                </div>
        <?
        ?>
            </form>
        </div>
        <script type="text/javascript">
            $j(document).ready(function() {
                $j("select.dropdown").change(function () {
                    $j(this).removeClass("place_holder");
                })
            });
        </script>
        <?
    }



    function get_arr_info_filters()
    { $info=parent::get_arr_info_filters() ;
        if ($this->filter['time_int'])                        $info['временной интервал']=$this->time_int[$this->filter['time_int']] ;
        if ($this->time_from)                                 $info['Анализ данных']='от '.date('d.m.Y',$this->time_from) ;
        else                                                  $info['Анализ данных']='за все время' ;
        if ($this->filter['theme_id'])                        $info['Тема КЗ']=QUIZ()->get_theme_name_by_id($this->filter['theme_id']);
        if ($this->filter['section_id'])                      $info['Раздел КЗ']=QUIZ()->get_theme_name_by_id($this->filter['section_id']);
//        if (_sizeof($this->filter['section_ids']))             $info['Раздел КЗ']=QUIZ()->get_theme_name_by_ids(implode(',',array_keys($this->filter['section_ids'])));
        if (MEMBER()->setting['personal']['usl_select'])     $info[MEMBER()->setting['personal']['name']]=strip_tags(MEMBER()->setting['personal']['info_filter']);
        return $info ;
    }



    function get_cnt_items($usl,$options=array()){return(1) ;}

    function get_items($usl,$options=array()){return(array()) ;}

    function prepare_data()
    {

        if (!$this->filter['theme_id']) {
            $level=2;
        } else {
            if (!$this->filter['section_id']) {
                $level=execSQL_value('select level from quiz_themes where pkey='.$this->filter['theme_id'])+1;
            } else {
                $level=execSQL_value('select level from quiz_themes where pkey='.$this->filter['section_id'])+1;
            }
        }

        $themes=execSQL('select pkey,clss,obj_name,parent,level from quiz_themes where level>0 order by level,parent');
//echo 'usl_quiz_result='.$this->usl_quiz_result.'<br>' ;
        $theme_stats=execSQL('select t2.parent as section_id,sum(t1.correct) as sum_correct,count(t1.quiz_result_id) as cnt 
                              from view_quiz_result t1 
                              inner join quiz_questions t2 on t2.pkey=t1.question_id
                              left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                              where '.$this->usl_quiz_result.' '.$this->usl_time.' and not tp.pkey is null
                              group by t2.parent ',2) ;

        $learned_stats=execSQL('select t2.parent as section_id,sum(t1.re_ask_result) as learned_sum_correct,count(t1.quiz_result_id) as learned_cnt
                          from view_quiz_learned t1
                          left join quiz_questions t2 on t2.pkey=t1.question_id
                         left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                          where '.$this->usl_quiz_result.' '.$this->usl_time.'  and not tp.pkey is null
                          group by t2.parent ',2) ;



        //если прямой родитель всех вопросов всего один
        if (_sizeof($theme_stats)==1) $this->view_as_question=1;

        //проверка что все прямые родители вопросов
        $cnt_sections=[];
        foreach ($theme_stats as $theme_stat) {
            $cnt_sections['cnt'][$themes[$theme_stat['section_id']]['parent']]++;
            if ($themes[$theme_stat['section_id']]['clss']==481) $cnt_sections['cnt_known'][$themes[$theme_stat['section_id']]['parent']]++;
        }
        if (_sizeof($cnt_sections['cnt'])==1 and _sizeof($cnt_sections['cnt_known'])) $this->view_as_question=1;

        //расчет данных только для вопросов
        if ($this->view_as_question)
        {

            $theme_stats=execSQL('select t1.question_id,sum(t1.correct) as sum_correct,count(t1.quiz_result_id) as cnt,t2.obj_name 
                          from view_quiz_result t1 
                          inner join quiz_questions t2 on t2.pkey=t1.question_id
                          left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                          where '.$this->usl_quiz_result.' '.$this->usl_time.'  and not tp.pkey is null
                          group by t1.question_id ') ;

            $learned_stats=execSQL('select t1.question_id,sum(t1.re_ask_result) as learned_sum_correct,count(t1.quiz_result_id) as learned_cnt,t2.obj_name 
                          from view_quiz_learned t1
                          left join quiz_questions t2 on t2.pkey=t1.question_id
                          left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                          where '.$this->usl_quiz_result.' '.$this->usl_time.'  and not tp.pkey is null
                          group by t1.question_id ') ;

            $themes=[];

            foreach ($theme_stats as $theme_stat) {
                $themes[$theme_stat['question_id']]['sum_correct']=$theme_stat['sum_correct'];
                $themes[$theme_stat['question_id']]['cnt']=$theme_stat['cnt'];
                $themes[$theme_stat['question_id']]['obj_name']=addslashes($theme_stat['obj_name']);
                $themes[$theme_stat['question_id']]['proc']=round(100*$theme_stat['sum_correct']/$theme_stat['cnt']);
            }

            foreach ($learned_stats as $learned_stat) {
                $themes[$learned_stat['question_id']]['learned_sum_correct']=$learned_stat['learned_sum_correct'];
                $themes[$learned_stat['question_id']]['learned_cnt']=$learned_stat['learned_cnt'];
                $themes[$learned_stat['question_id']]['obj_name']=addslashes($learned_stat['obj_name']);
                $themes[$learned_stat['question_id']]['learned_proc']=round(100*$learned_stat['learned_sum_correct']/$learned_stat['learned_cnt']);
            }
        } else {
            $theme_stats_full=execSQL('select t2.parent as section_id,count(t2.pkey) as cnt_question
                               from quiz_questions t2
                               group by t2.parent') ;

            $max_level=0;
            foreach ($themes as $key=>&$theme) {
                if ($theme['level']>$max_level) $max_level=$theme['level'];
                if (_sizeof($theme_stats[$key])) $theme=array_merge($theme,$theme_stats[$key]);
                if (_sizeof($learned_stats[$key])) $theme=array_merge($theme,$learned_stats[$key]);
                if (_sizeof($theme_stats_full[$key])) $theme=array_merge($theme,$theme_stats_full[$key]);
            }



            if ($max_level>0) {
                for ($i=$max_level;$i>0;$i--) {
                    foreach ($themes as $key=>$theme) {
                        if ($theme['level']!=$i) continue;
                        if (!$theme['cnt']) {
                            unset($themes[$key]);
                            continue;
                        }
                        if ($theme['parent']) {
                            $themes[$theme['parent']]['sum_correct']+=$theme['sum_correct'];
                            $themes[$theme['parent']]['cnt']+=$theme['cnt'];
                            $themes[$theme['parent']]['learned_sum_correct']+=$theme['learned_sum_correct'];
                            $themes[$theme['parent']]['learned_cnt']+=$theme['learned_cnt'];
                            $themes[$theme['parent']]['cnt_question']+=$theme['cnt_question'];
                        }
                    }
                }
            }

            foreach ($themes as $key=>&$theme) {
                if ($theme['level']!=$level) {
                    unset($themes[$key]);
                    continue;
                }
                if ($theme['cnt']) $theme['proc']=round(100*$theme['sum_correct']/$theme['cnt']);
                if ($theme['learned_cnt']) $theme['learned_proc']=round(100*$theme['learned_sum_correct']/$theme['learned_cnt']);
            }
        }

        return $themes;
    }

    function calculate_data_proc(&$data_set)
    {
        foreach ($data_set as &$data) {
            $data['proc']=($data['cnt_questions_get'])? $data['cnt_questions_get_correct']/$data['cnt_questions_get']*100:0 ;
            $data['proc']=($data['proc']>=1)? round($data['proc']):round($data['proc'],1) ;

            if (!empty($data['cnt_learned_get'])) {
                $data['proc_learned']=$data['cnt_learned_get_correct']/$data['cnt_learned_get']*100 ;
                $data['proc_learned']=($data['proc_learned']>=1)? round($data['proc_learned']):round($data['proc_learned'],1) ;
            }

            if (is_array($data['section_stats']) and _sizeof($data['section_stats'])) {
                $this->calculate_data_proc($data['section_stats']);
            }
        }
    }

    function prepare_chart_data($arr_result)
    {
        $result=[];

        $result['knowledge']['caption']='Уровень знаний';
        $result['learned']['caption']='Усваиваемость';

        foreach ($arr_result as $rec) {
            if (isset($rec['proc'])) {
                $result['knowledge']['category'][]=$rec['obj_name'];
                $result['knowledge']['data'][]=$rec['proc'];
            }
            if (isset($rec['learned_proc'])) {
                $result['learned']['category'][]=$rec['obj_name'];
                $result['learned']['data'][]=$rec['learned_proc'];
            }
        }

        return $result;
    }

    function print_template_HTML($list_recs,$options=array())
    {

        $arr_result=$this->prepare_data();

        $chart_arr=$this->prepare_chart_data($arr_result);

        $this->print_charts($chart_arr,$options);

//        damp_array($arr_result);

        ?><table class="basic full auto" >
        <tr>
            <?
            if (!$this->view_as_question) {
                ?>
                <th>Тема/Раздел</th><th>Число вопросов в теме/разделе</th>
                <?
            } else {
                ?>
                <th>Вопрос</th>
                <?
            }
            ?>
            <th>Число заданных вопросов</th>
            <th style="width:210px;">Процент правильных ответов</th>
            <th>Кол-во переспросов</th>
            <th>Процент усваиваемости</th>
            <!--<th>Процент покрытия темы/раздела</th>-->
        </tr><?
        if (_sizeof($arr_result)) foreach($arr_result as $id=>$rec)
        {
            $filter_params=[];
            if (!$this->filter['theme_id']) {
                $filter_params['theme_id']=$rec['pkey'];
            } else {
                if (!$this->view_as_question) {
                    $filter_params['section_id']=$rec['pkey'];
                }
            }
            ?>
            <tr class=item style="background-color:rgba(0,80,170,0.65);color:white;">
                <td class="left section_name">
                <?
                     if (!$this->view_as_question) echo '<a href="'.$this->get_filter_to_params($filter_params,['url_report'=>_CUR_REPORT_DIR]).'">'.$rec['obj_name'].'</a>' ;
                     else echo '<a href="/window/quiz/question/card/'.$id.'/" class="new_window">'.$rec['obj_name'].'</a>' ;
                ?>
                </td>
            <?
            if (!$this->view_as_question)
            {?><td class=""><?echo $rec['cnt_question']?></td><?}?>
                <td class=""><?echo $rec['cnt']?></td>
                <td class=""><?echo $rec['proc']?>%</td>
                <td class=""><?echo $rec['learned_cnt']?></td>
                <td class=""><?if (isset($rec['learned_proc'])) echo $rec['learned_proc'].'%'?></td>
            </tr>
            <?
        }
        ?></table>
        <?
        //damp_array($rec);
        ?>
        <style>
            /*td.section_name { position: relative; }*/
            td.section_name a{
                /*position: absolute;*/
                /*left: 0; right: 0;*/
                /*top: 0; bottom: 0;*/
                color: white;
                /*margin: 3px;*/
                /*text-decoration: none;*/
            }
        </style>
        <?
    }

    function print_charts($arr,$options=[]) {
        ?>
        <div class="charts">
            <div class="radar_chart" id="radar_chart_1"></div>
            <div class="radar_chart" id="radar_chart_2"></div>
            <?if ($options['stats_elem_id']){?><div class="stats_chart" id="<?=$options['stats_elem_id']?>"></div><?}?>
        </div>
        <style type="text/css">
            .charts{
                display:flex;
                margin:0 auto;
                width:100%;
                min-height: 300px;
            }
            .charts div.radar_chart {
                <?if ($options['stats_elem_id']){ echo 'width: 30%;';} else { echo 'width: 50%;';}?>
            }
            <?if ($options['stats_elem_id']){?>
            .charts div.stats_chart {
                width: 40%;
            }
            <?}?>
        </style>
        <?

        $this->create_radar_chart($arr['knowledge'],'radar_chart_1');
        $this->create_radar_chart($arr['learned'],'radar_chart_2');
    }



    function create_radar_chart($data,$elem_id) {
        if(!_sizeof($data)) return;
//        damp_array($data);
        ?>
        <script type="text/javascript">
            $j(document).ready(function() {
                var <?='js_'.$elem_id?> = new FusionCharts({
                    type: 'radar',
                    renderAt: <?=$elem_id?>,
                    width: '100%',
                    height: '300',
                    dataFormat: 'json',
                    dataSource: {
                        "chart": {
                            "caption": "<?=$data['caption']?>",
                            "subCaption": "",
                            "theme": "fusion",
                            "showvalues": "0",
                            "numberSuffix": "%",
                            "plotfillalpha": "60",
                            // "animation": "0",
                            "yAxisMaxValue": "100",
                            "yAxisMinValue": "100",
                            "showBorder" : "0",
                            "bgColor" : "#ffffff",
                            "palettecolors": "#0050aa"
                        },
                        // Chart Data
                        categories: [
                            {
                                category: [ <? foreach ($data['category'] as $value) { echo '{"label": "'.$value.'"},';} ?>]
                            }
                        ],
                        dataset: [
                            {
                                seriesname: "",
                                color: "#2da5da",
                                data: [ <? foreach ($data['data'] as $value) { echo '{"value": "'.$value.'"},';} ?>]
                            }
                        ]
                    }
                });

                <?='js_'.$elem_id?>.render();
            });
        </script>
        <?
    }

    function hierarchy_array($arr,$prev_parent=0) {
        $temp_arr=[];
        foreach ($arr as $key=>$value) {
            if ($value['parent']==$prev_parent) {
                $temp_arr[$key]=$value;
                $temp_arr2=$this->hierarchy_array($arr,$value['pkey']);
                if (_sizeof($temp_arr2)) $this->merge_arr($temp_arr,$temp_arr2);
            }
        }
        return $temp_arr;
    }

    function merge_arr(&$arr1,$arr2)
    {
        if (_sizeof($arr1)) {
            foreach ($arr2 as $key=>$value) {
                $arr1[$key]=$value;
            }
        } else {
            $arr1=$arr2;
        }

    }

    function empty_space($level) {
        $min=4;
        $result='';
        if ($level>=$min) {
            for ($i=$min;$i<=$level;$i++) {
                $result.='&nbsp;&nbsp;&nbsp;';
            }
        }
        return $result;
    }

}

?>
