1)I有一個菜單包括菜單項,每一個與一個order_index(範圍從0到n),其識別在所述菜單項的位置菜單。
2)我想插入一個新的菜單項在一個特定的位置或改變現有元素的位置。
3)假設如果它是一個新項目,我已經用order_index = null將新項目保存在我的數據庫中。
4)因此,當編輯/創建的菜單項,比order_index其他所有相關信息獲取,保存,然後下面的函數被調用:
function reOrderItems(MenuItem $item, Integer $orderIndex)
{
/*
Step 1: Retrieve all the MenuItems, ordered by order_index. This means that
If it was a new item, the item's order_index is null and would be the
first item in the array of retrieved items.
Step 2: Take the item ($item) and remove it from its current location in the
array and place it at its new position, $orderIndex.
Step 3: "Reorder" the array indexing so that it runs from 0 to
(array.length - 1) in the order that the Menu Items are now.
Step 4: Update all items in the database with their new order_index, ranging
from 0 to n according to the array index.
*/
}
實施例1:移動物品在位置[0]至位[3]。 [1] => [0],[2] => [1],[3] => [2],[0] => [3]並且所有其他元素保持相同。
示例2:將位置[6]中的項目移動到位置[3]。 位置[0],[1]和[2]中的項目保持不變。 [3] => [4],[4] => [5],[5] => [6],[6] => [3],所有其他元素保持不變。
我將不勝感激任何幫助一個算法,將能夠爲我做的步驟2 & 3。請記住,真正的天才在於簡單。實現這一點的算法越簡單越好。
認罪se通過調用'print_r()'菜單作爲參數來添加一個菜單的例子。 –