无限分类导出排序问题

我有一个表,agents,用来做有无限下线的代理表。里面用一个parent字段来记录上级代理的id。现在要做xls导出,但是我想的是导出的结果要能正常导入进去,所以,需要上级代理排在下级代理的前面。

经过我处理后的数据是:

$agents = json_decode('[{"id":7,"name":"\u5f20\u4e09","parent":0},{"id":8,"name":"\u674e\u56db","parent":7},{"id":9,"name":"\u738b\u4e94","parent":7},{"id":10,"name":"\u9a6c\u516d","parent":9},{"id":11,"name":"\u674e\u56db\u4e00","parent":12},{"id":12,"name":"\u738b\u4e94\u4e00","parent":18},{"id":15,"name":"\u6797\u9038","parent":9},{"id":16,"name":"\u6768\u660e","parent":15},{"id":17,"name":"\u6797\u4e1c\u65b9","parent":16},{"id":18,"name":"\u5c0f\u7070\u7070","parent":15},{"id":19,"name":"\u6d4b\u8bd5","parent":0}]');

我使用的排序方法是:

$agents = collect($agents)->sort(function ($a, $b) {
    return $a['parent '] == $b['id'] 1 : -1;
});

但是并没有什么作用。

正常的分类树应该是这个样子。

sort.jpg