我需要帮助弄清楚如何使用PHP将数组项目移动到一个位置。到目前为止,PHP如下:
<?php
$task_list = array();
$task_list[] = 'Write chapter';
$task_list[] = 'Edit chapter';
$task_list[] = 'Proofread chapter';
switch( $_POST['action'] ) {
case 'Promote Task':
//This is where I'm stuck.
?>
和HTML:
<?php if (count($task_list) > 0 && empty($task_to_modify)) : ?>
<h2>Select Task:</h2>
<form action="." method="post" >
<?php foreach( $task_list as $task ) : ?>
<input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/>
<?php endforeach; ?>
<label>Task:</label>
<select name="taskid">
<?php foreach( $task_list as $id => $task ) : ?>
<option value="<?php echo $id; ?>">
<?php echo $task; ?>
</option>
<?php endforeach; ?>
</select>
<br />
<label> </label>
<input type="submit" name="action" value="Modify Task"/>
<input type="submit" name="action" value="Promote Task"/>
<input type="submit" name="action" value="Delete Task"/>
非常感谢任何帮助!
答案 0 :(得分:0)
您只需要交换两行(选定的任务和上面的任务)。因此,如果您的索引始终为0,1,2,3,..,n:
$selectedRow = $_POST['taskid'];
if ($selectedRow === 0) {
echo 'Already top-priority';
} else {
$rowAbove = $taks_list[$selectedRow - 1];
$task_list[$selectedRow - 1] = $taks_list[$selectedRow];
$task_list[$selectedRow] = $rowAbove;
// Or without help-variable, but less readable
list($task_list[$selectedRow - 1], $task_list[$selectedRow])
= array($task_list[$selectedRow], $task_list[$selectedRow - 1]);
}