我正在向服务器端发送一个对象数组,用于拖放菜单排序。我想将每个菜单项的 parent_id 和排序值更新到我的数据库中,所有根项目父项将为0,但我无法正确定义我的函数。
[
{
"id": 2,
"children": [
{
"id": 1,
"children": [
{
"id": 3,
"children": []
}
]
}
]
},
{
"id": 4,
"children": [
{
"id": 5,
"children": []
}
]
}
]
我试过
public static function sort($menus, $parent_id = 0)
{
$i = 0;
foreach ($menus as $menu) {
$menuItem = MenuItem::find($menu['id']);
$menuItem->parent_id = $parent_id;
$menuItem->sort = $i;
$menuItem->save();
$i += $i;
if (count($menu['children'])) {
MenuController::sort($menus, $menu['id']);
}
}
}
public function postSaveMenuOrder(Request $request)
{
if ($request->has('menu-data')) {
$menuData = $request->get('menu-data');
MenuController::sort($menuData);
}
}
答案 0 :(得分:0)
您的数组包含对象,但您尝试将它们用作数组:
public static function sort($menus, $parent_id = 0)
{
foreach ($menus as $key => $menu) {
$menuItem = MenuItem::find($menu->id);
$menuItem->parent_id = $parent_id;
$menuItem->sort = $key;
$menuItem->save();
if (count($menu->children)) {
// note that here we are passing the children of the menu,
// not all the menus as in your example
self::sort($menu->children, $menu->id);
}
}
}
您也可以使用密钥而不是$i
变量。