我想从这个数组(PHP Laravel)中获取id和parent_id的值来更新数据库。
stdClass Object( [item_id] => [parent_id] => [depth] => 0 [left] => 1 [right] => 12)
stdClass Object( [id] => 1 [parent_id] => [depth] => 0 [left] => 2 [right] => 3)
stdClass Object( [id] => 2 [parent_id] => [depth] => 0 [left] => 4 [right] => 5)
stdClass Object( [id] => 4 [parent_id] => [depth] => 0 [left] => 6 [right] => 7)
stdClass Object( [id] => 5 [parent_id] => [depth] => 0 [left] => 8 [right] => 11)
stdClass Object( [id] => 6 [parent_id] => 5 [depth] => 1 [left] => 9 [right] => 10)
控制器:
public function updatemenusort(Request $request)
{
$menus=json_decode($request->input('menu'));
foreach($menus as $menu)
{
print_r($menu);
}
}
来自观看的ajax:
$('#toArray').click(function (e) {
arraied = $('ol.sortable').nestedSortable('toArray', {startDepthCount: 0});
//arraied = dump(arraied);
arraied = JSON.stringify(arraied);
// ajax strt
alert(arraied);
$.ajax({
type: 'POST',
url: "{{url('menus/sortmenu')}}",
dataType: 'json',
data: {'menu': arraied, '_token': _token},
success: function (data) {},
error: function (data) {}
});
});
我尝试使用this插件创建可拖动且可排序的菜单。
上面的数组是我的控制器的(print_r($menu);)
输出。
答案 0 :(得分:0)
您已遍历对象数组,因此现在将$menu
设置为单个对象实例。
因此,只需将数据作为对象及其属性进行访问。
public function updatemenusort(Request $request)
{
$menus=json_decode($request->input('menu'));
foreach($menus as $menu)
{
echo $menu->id;
if ( isset($menu->parent_id) {
echo $menu->parent_id;
} else {
echo 'No parent Id';
}
// etc etc
// In your case I assume you would want to
// build a query here and not just echo data,
// but thats just a FLOC
}
}
答案 1 :(得分:0)
这可能对您有所帮助
public function updatemenusort(Request $request)
{
foreach($request->menu as $menu)
{
// if you are finding by id
$model = ModelName::find($menu['id']); // can use findOrFail()
// checking if not null
if (!is_null($model)) { // remove if using findOrFail()
$model->id = $menu['id'];
$model->parent_id = $menu['parent_id'];
$model->save();
}
/*---------------------or---------------------*/
// creating new but here you might get duplicate id error
$model = new ModelName;
$model->id = $menu['id'];
$model->parent_id = $menu['parent_id'];
$model->save();
}
}
以前的建议这与上述
无关您可以使用array_column()
。如果你想在新数组中使用id
和parent_id
。
例如
$ids = array_column($menus, 'id'); // for id
$parentId = array_column($menus, 'parent_id'); // for parent id
<强>建议强>
我不知道您为什么使用arraied = JSON.stringify(arraied);
只是按原样传递对象并在控制器中
//$menus=json_decode($request->input('menu')); // no need to use json_decode() if you are doing to get as object then you can do like
$menus= $request->input('menu');
foreach($menus as $menu)
{
$menu = (object) $menu; // you can cast here
print_r($menu);
}