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

问题描述 投票:0回答:1

以下示例用于填充树并使用带有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 函数进行了一些尝试(没有成功)。

有什么方法可以用雄辩的方式解决,同时记住子节点的数量可以是无限的?

谢谢。

编辑:

使用 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){
    ???
}
php laravel recursion hierarchical-data
1个回答
1
投票

您可以递归使用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();
© www.soinside.com 2019 - 2024. All rights reserved.