2012-11-10 51 views
0

我正在嘗試在PHP中使用圖片庫管理移除過程。我一直在how on如何更新列表順序,以便在刪除後保持相同的順序。使用php更新排序?

我有一個關聯數組($ images),其中鍵與'order'值相同,這個數字定義了庫中的位置。我也有一個應該刪除的訂單號列表,通過用訂單號識別它來刪除每個圖像。圖像

$images format 

array(28) { 
[1]=> 
    array(5) { 
    ["gallery_id"]=> 
    string(2) "71" 
    ["property_id"]=> 
    string(1) "3" 
    ["picture"]=> 
    string(17) "imgname.jpg" 
    ["order"]=> 
    string(1) "1" 
    ["alt_text"]=> 
    string(14) "discription" 
    } 
[2]=> 
    array(5) { 
    ["gallery_id"]=> 
    string(2) "83" 
    ["property_id"]=> 
    string(1) "3" 
    ["picture"]=> 
    string(17) "imgname.jpg" 
    ["order"]=> 
    string(1) "2" 
    ["alt_text"]=> 
    string(14) "discription" 
    } 
So on... how ever large the list might be. 

列表以刪除

$removedImgs 

array(2) { 
    [0]=> string(1) "1" 
    [1]=> string(1) "3" 
} 

上面顯示圖像1和3將從圖庫

Current: 1 2 3 4 5 6 ... 
Removal: 2 4 5 6 
      | | | | 
Reordering: 1 2 3 4 

實際移除代碼去除

// Loop though with each image and remove the ones posted from the list 
foreach ($_POST['orderID'] as $removeImg) 
{ 
    // Store each removed images order id 
    $removedImgs[] = $removeImg; 

    // If we're removing images create a list of the image paths to 
    // unlink the files later. 
    if (isset($images[$removeImg])) 
    { 
     $unlinkList[] = $imgPath . $images[$removeImg]['picture']; 
     $unlinkList[] = $imgPath . 'thumbs/thumb' . $images[$removeImg]['picture']; 
    } 

    // $images should only contain the ones that we haven't removed. 
    unset($images[$removeImg]); 

    // Update the image order 
    foreach ($images as $key => &$img) 
    { 
     if ($key > $removeImg) 
     { 
      (int)$img['order']--; 
     } 
    } 
    var_dump($images); 
    echo "\n\n==========\n\n"; 
} 
+0

這真是令人困惑。 – Ben

回答

1

如果你對ima的時候有控制權ges被刪除,那麼當時更新訂單的時間會更容易。

function removeImage($images, $imgName) 
{ 
    $removedImgNum = $images[$imgName]['order']; 
    $images[$imgName] = undefined; // or delete, etc 

    foreach ($images as $img) 
    { 
     if ($img['order'] > $removedImgNum) 
      $img['order']--; 
    } 
} 
+0

我的確想到了這一點,但希望看看是否有更好的方法,而不是每次循環列表。我只是實現了這一點,但正在尋找,看看我是否可以想出更好的選擇,並認爲我已與removedCounter變種。謝謝,如果我確實想到一個更好的方式,儘管列表一旦我將它作爲解決方案發布在這裏。 – LF4

0

不知道我理解,但也許這兩個陣列,和array_diff_assoc ()比較,然後用ksort()會做你想做的排序結果。