简体   繁体   中英

Move array element up one place PHP

I need help figuring out how to move a array item up one place using PHP. The PHP so far is as follows:

<?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:

<?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:

$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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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