假設你有輸入這樣的:
$item_id = array(1, 2, 3);
$item_order = array(2, 1, 3);
// and a PDO connection named $pdo
你可以嘗試這樣的事情。 (我還假設你的PDO配置爲throw exceptions when problems arise)。
function all_numbers($input) {
foreach($input as $o) {
if(!is_numeric($o)) {
return false;
}
}
return true;
}
if(count($item_id) != count($item_order)) {
throw new Exception("Input size mismatch!");
}
if(!all_numbers($item_id) || !all_numbers($item_order)) {
throw new Exception("Invalid input format!");
}
$pairs = array_combine($item_id, $item_order);
// now $pairs will be an array(1 => 2, 2 => 1, 3 => 3);
if($pdo->beginTransaction()) {
try {
$stmt = $pdo->prepare('UPDATE `items` SET `item_order` = :order WHERE `item_id` = :id');
foreach($pairs as $id => $order) {
$stmt->execute(array(
':id' => $id,
':order' => $order,
));
}
$pdo->commit();
} catch (Exception $E) {
$tx->rollback();
throw $E;
}
} else {
throw new Exception("PDO transaction failed: " . print_r($pdo->errorInfo(), true));
}
但它可能是更好的重新設計你的輸入 - 僅在傳遞所需順序item_ids
,並自動計算其item_order
值。
感謝DCoder,請試試看。但是,您準確地重新確定輸入的含義是什麼?你能給我舉個例子嗎? – Wonka
@Wonka:我的意思是,您應該按照正確的順序傳遞id,並讓插入循環生成實際的$ order值。看看[jQuery Sortable的'toArray'](http://jqueryui.com/demos/sortable/#method-toArray)方法。 – DCoder
作品像一個魅力,謝謝你的幫助! – Wonka