<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\library\utils;

/**
 * @package app\common\library\utils
 * @class Data
 * @author xzncit 2023-09-04
 */
class Data {

    /**
     * @param $data
     * @param int $id
     * @return array
     */
    public static function getTree($data,$id=0) {
        $tree = [];
        while ($id > 0) {
            foreach ($data as $v) {
                if ($v['id'] == $id) {
                    $tree[] = $v;
                    $id = $v['pid'];
                    break;
                }
            }
        }

        return $tree;
    }

    /**
     * @param $result
     * @param $data
     * @return bool
     */
    public static function checkTree($result, $data) {
        $tree = self::getTree($result, $data["pid"]);

        $flag = true;
        foreach ($tree as $v) {
            if ($v['pid'] == $data["id"]) {
                $flag = false;
                break;
            }
        }

        return $flag;
    }

    /**
     * @param $data
     * @param array $res
     * @param string $pid
     * @return array|mixed
     */
    public static function familyProcess($data,$res=[],$pid='0'){
        foreach($data as $item){
            if($item['pid'] == $pid){
                $res[$item['id']] = $item;
                $res[$item['id']]['children'] = self::familyProcess($data,[],$item['id']);
            }
        }

        return $res;
    }

    public static function analysisTree($data,$res=[]){
        foreach($data as $item){
            $value = $item;
            unset($value["children"]);
            $res[] = $value;
            if(!empty($item["children"])){
                $res = array_merge($res,self::analysisTree($item["children"],[]));
            }
        }

        return $res;
    }

    public static function descarte($arr, $tmp = []) {
        static $n_arr = [];
        foreach (array_shift($arr) as $v) {
            $tmp[] = $v;
            if ($arr) {
                self::descarte($arr, $tmp);
            } else {
                $n_arr[] = $tmp;
            }
            array_pop($tmp);
        }

        return $n_arr;
    }

}