我想知道如何根据这种类型的数据更新我的数据库:
Array
(
[0] => Array
(
[id] => 58
[children] => Array
(
[0] => Array
(
[id] => 62
[children] => Array
(
[0] => Array
(
[id] => 61
)
)
)
)
)
[1] => Array
(
[id] => 60
[children] => Array
(
[0] => Array
(
[id] => 63
)
)
)
[2] => Array
(
[id] => 0
[children] => Array
(
[0] => Array
(
[id] => 59
)
)
)
)
我尝试了不同的方法,但它没有按预期工作。
这是保存列表新订单的函数,我使用nestedSortable('toHierarchy')
function order()
{
$list = $_POST['list'];
foreach ($list as $key => $value) {
if(is_array($value['children'])) {
$i=1;
foreach($value['children'] as $k=>$v) {
$this->section->edit(array('order' => $i, 'parent_id'=>$value['id']),
"WHERE `id`=" . $v['id']);
echo 'parent '.$value['id'].'child->'.$v['id'].' order->'.$i.'<br/>';
$i++;
}
}
else {
$this->section->edit(array('order' => $key, 'parent_id'=>0),
"WHERE `id`=" . $value['id']);
}
}
}
但它不适用于超过2级的列表。
这是js我正在使用
$('ol.sortable').nestedSortable({
update : function () {
var orderNew = $(this).nestedSortable('serialize', {startDepthCount: 0});
//alert(orderNew);
$.ajax({
type: 'post',
url: '<?php echo (APP_URL); ?>projects/<?php echo $project_id; ?>/sections/order_list',
data: {list:orderNew}
});
},
disableNesting: 'no-nest',
forcePlaceholderSize: true,
handle: 'div',
helper: 'clone',
items: 'li',
maxLevels: 4,
opacity: .6,
placeholder: 'placeholder',
revert: 250,
tabSize: 25,
tolerance: 'move',
toleranceElement: '> div'
});
答案 0 :(得分:1)
您可以实现递归函数来处理无限的嵌套级别。但我建议使用嵌套的可排序serialize
方法作为替代方法:
$('your_sortable_selector').nestedSortable('serialize');
这会生成一个平面数组,其中键为项ID ,每个键的值为父ID 。然后,您可以实现一个不那么复杂的功能:
function order()
{
$list = $_POST['list'];
// an array to keep the sort order for each level based on the parent id as the key
$sort = array();
foreach ($list as $id => $parentId) {
/* a null value is set for parent id by nested sortable for root level elements
so you set it to 0 to work in your case (from what I could deduct from your code) */
$parentId = ($parentId === null) ? 0 : $parentId;
// init the sort order value to 1 if this element is on a new level
if (!array_key_exists($parentId, $sort)) {
$sort[$parentId] = 1;
}
$this->section->edit(array('order' => $sort[$parentId], 'parent_id' => $parentId), "WHERE `id`= $id");
// increment the sort order for this level
$sort[$parentId]++;
}
}
这适用于任何数量的嵌套级别。