简体   繁体   English

将数组元素上移PHP

[英]Move array element up one place PHP

I need help figuring out how to move a array item up one place using PHP. 我需要帮助弄清楚如何使用PHP将数组项上移一位。 The PHP so far is as follows: 到目前为止,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.
?>

and the HTML: 和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>&nbsp;</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"/>

Any help would be much appreciated! 任何帮助将非常感激!

You only need to swap two rows (the selected task, and the task above). 您只需要交换两行(所选任务以及上面的任务)。 So if your indexes always are 0, 1, 2, 3, .., n: 因此,如果您的索引始终为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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM