分类数组进行切分
//测试叶子节点 public function trees(){ $result = AliexpressCategories::where('state', 1)->get(['cate_id', 'ali_cate_id', 'ali_cate_parent_id', 'isleaf'])->toarray(); $leafData = []; $allData = []; if (!empty($result) && is_array($result)) { foreach ($result as $k => $v) { if ($v['isleaf']) { //是否为叶子节点 $leafData[$v['ali_cate_id']] = $v;//把目录id所为key值。对应数据作为value值 } else { $allData [$v['ali_cate_id']] = $v; } } unset($result); $this->data = $allData; // unset($allData); foreach ($leafData as $cateId => &$item) { $trees = $this->getAttrTree($item);//找这个节点的上级数组, var_dump($trees);die; if (!empty($trees)) { $item['aliexpress_tree'] = implode(",", array_reverse(explode(',', $trees))); $item['updated_at'] = date('Y-m-d H:i:s');; } } $object = (new AliexpressCategories());
//collect->chunk(100) 将集合拆成多个给定大小的较小集合: 把数组切割成多个数值,然后进行遍历,避免数据太大,请求超时 foreach (collect($leafData)->chunk(100) as $child_collect) { $object->updateBatch($child_collect->toArray()); } return true; } }
//方法获取节点对应上级
function getAttrTree($item, $tree = '')
{
$cateTree = $tree ? ($tree . ',' . $item['ali_cate_id']) : $item['ali_cate_id'];
if ($item['ali_cate_parent_id'] && isset($this->data[$item['ali_cate_parent_id']])) {
return $this->getAttrTree($this->data[$item['ali_cate_parent_id']], $cateTree);
}
return $cateTree;
}
表结构