<?php

namespace App\Utils;

class FormatUtils
{
    /**
     * 格式化为树形结构
     * @param $menus
     * @param $parentValue
     * @param string $juniorTitle //下级标题
     * @param string $parentKey
     * @param string $subKey
     * @param string $useKey
     * @return array
     */
    public static function formatTreeData($menus, $parentValue, $juniorTitle = 'children', $parentKey = 'parent_id', $subKey = 'id', $useKey = '')
    {
        $data = [];
        foreach ($menus as $menu) {
            if ($menu[$parentKey] == $parentValue) {
                $res = self::formatTreeData($menus, $menu[$subKey], $juniorTitle, $parentKey, $subKey, $useKey);
                if (!empty($res)) {
                    $menu[$juniorTitle] = $res;
                }

                if ($useKey) {
                    $data[$menu[$useKey]] = $menu;
                } else {
                    $data[] = $menu;
                }
            }
        }
        return $data;
    }
}
