从递归查询的结果中获取某些属性数据

Get certain attribute data from the result of a recursive query

以下示例用于填充树并使用 table 和 parent_id 列。

数据是通过递归查询得到的

$data = [{
    "id": 1,
    "name": "parent 1"
    "note": "note 1",
}, {
    "id": 2,
    "name": " parent 2",
    "note": "note 2",
    "children": [{
        "id": 21,
        "name": "child A of 2",
        "note": "note A of 2",
    },{
        "id": 22,
        "name": "child B of 2",
        "note": "note B of 2",
    },{
        "id": 23,
        "name": "child C of 2",
        "note": "note C of 2",
        
        "children": [{
            "id": 231,
            "name": "child A of 23",
            "note": "note A of 23",

            "children": [{
                "id": 2311,
                "name": "child A of 231",
                "note": "note A of 231",

                "children": []
            }]
        }]
    }]
}];

以及查询:

$myData= Hierarchy::whereNull('parent_id')
                  ->with('children')
                  ->get();

到目前为止一切顺利。

要解决的问题:

需要获取父子id和name属性的简单(非分层)列表。

示例:

"id": 1,
"name": "parent 1",
"id": 2,
"name": " parent 2",
"id": 21,
"name": "child A of 2",
"id": 23,
"name": "child C of 2",
"id": 231,
"name": "child A of 23",
"id": 2311,
"name": "child A of 231"

虽然这可以在客户端使用 javascript 解决,但我打算使用 eloquent 或 PHP 函数来解决。

我尝试使用 array_walk() 和 array_walk_recursive() PHP 函数(没有成功)。

有什么办法可以用eloquent解决吗,注意子节点的个数可以是无限的?

谢谢。

已编辑:

使用 array_walk_recursive() PHP 函数的示例尝试

public function getList() 
{
    $myData= Hierarchy::whereNull('parent_id')
                  ->with('children')
                  ->get();
    
    $data = array_walk_recursive($myData, "self::myFunction");

    return response()->json(['success' => true, "data" => $data]);
}

public function myFunction($item, $key){
    ???
}

您可以使用API Resouce递归或使用递归函数生成层级数组。

带有递归函数的示例:

function makeHierarchy($values) 
{
    $result = [];

    foreach($values as $item) {
        $result[] = [
            'id' => $item->id,
            'name' => $item->name,
            'children' => makeHierarchy($item->children),
        ];
    }

    return $result;
}

$values = Hierarchy::whereNull('parent_id')->with('children')->get();
$hierarchical = makeHierarchy($values);

如果您想将所有值作为平面列表获取:

$values = Hierarchy::get();
$result = [];

foreach($values as $item) {
    $result[] = [
        'id' => $item->id,
        'name' => $item->name,
    ];
}

# now the result contains all the parents and children in a flat list

更简洁的方式:

$result = Hierarchy::select(['id', 'name'])->all();