参考:https://blog.youkuaiyun.com/frankcheng5143/article/details/52958486
/**
* 获取所有分类
* @return
*/
public final String allCategories() {
// 获取到原始数据
List<CategoryPOJO> list = new ArrayList<>();
//获取到所有的数据
List<BPEProductCategory> thePrimaryCategories = categoryDAO.allCategories();
for (BPEProductCategory c : thePrimaryCategories) {
CategoryPOJO pojo = new CategoryPOJO();
pojo.setId(c.id);
pojo.setSortOrder(c.sortOrder);
pojo.setAmount(productListDAO.numberOfItemsByCategory(c.id));
pojo.setProductCategoryName(c.productCategoryName);
pojo.setProductCategoryParentsId(c.productCategoryParentsId);
list.add(pojo);
}
// 最后的结果
List<CategoryPOJO> categoryList = new ArrayList<>();
// 找到所有的一级菜单
for (CategoryPOJO categoryPOJO : list) {
if(categoryPOJO.getProductCategoryParentsId()!=null) {
if (categoryPOJO.getProductCategoryParentsId().equals("0")) {
// 找到所有的一级菜单
categoryList.add(categoryPOJO);
}
}
}
// 为一级菜单设置子菜单
for (CategoryPOJO categoryPOJO : categoryList) {
categoryPOJO.setChildren(this.getChild(categoryPOJO.getId(), list));
}
Msg msg = new Msg();
msg.setData(categoryList);
return toJSON(msg);
}
/**
* 获取子菜单
*
* @param id
* @param getdata
* @return
*/
public List<CategoryPOJO> getChild(String id, List<CategoryPOJO> getdata) {
// 子菜单
List<CategoryPOJO> childList = new ArrayList<>();
// 将传过来的id与这里的父id比较
for (CategoryPOJO categoryPOJO : getdata) {
if (id.equals(categoryPOJO.getProductCategoryParentsId())) {
childList.add(categoryPOJO);
}
}
// 把子菜单的子菜单再循环一遍 (递归)
for (CategoryPOJO categoryPOJO : childList) {
categoryPOJO.setChildren(getChild(categoryPOJO.getId(), getdata));
}
// 递归退出条件
if (childList.size() == 0) {
return null;
}
return childList;
}