Sort sequence of numbers in database with PHP

5

I'm having trouble developing a system that changes a sequence of numbers. I need this sequence to arrange items in the correct order. When saving an item in the bank, it receives a number for the sequence 1, 2, 3 ... and so on.

I decided to modify and try to explain better, the list below, comes from a database, the first number only shows the id of the bank the second in the order in which they were saved, the rest is just description. I want to know how to modify this order by clicking one of the items. In the photo item 2 is selected, in that case, when I click the up arrow I want 2 to be 1 and 1 to be 2. How can I do this algorithm?

$mo = $maxOrder - 1; //ultima numeração de ordem da materia menos 1

        if($ordem == 1){ //se ordem atual for o primeiro registro

            $result = $ordem + $mo; //soma-se ortem atual com $mo para ficar por ultimo

        }elseif($ordem == $maxOrder){ //ou se ordem for a ultima

            $result = $ordem - 1; //subtrai-se por 1 para passar a ser a primeira

        }else{
            $result = $ordem + 1; //senão soma-se com 1 para subir
        }

ToretrievethisdataIsendarequestthroughtheangletothefunctionbelow,init,Icallthemodelthatmakestheselect,storetheresultinanobjectandthenscrolltheobjectwithaforeachandstoretheresultinarrayofNameDate.afterthatreturnthedataviajsonwithjson_encode().Hereisthecodequoted:

publicfunctiongetMateriaByPortaria(){$this->layout=""; //retornar dados numa tela sem layout

  $materias = $this->PortariaMateriaM->get_all_portaria_materia(); //pega todos os dados da tabela portaria_has_materia

  $data = array(); //array data

  foreach ($materias as $mat) { //foreach que percorre o objeto e armazena no array data
        $data[] = array(
            "idportaria_materia" => $mat->idportaria_materia,
            "ordem" => $mat->ordem,
            "numerada" => $mat->numerada,
            "idportaria" => $mat->idportaria,
            "data_inicio" => $mat->data_inicio,
            "data_fim" => $mat->data_fim,
            "titulo" => $mat->titulo,
            "descricao" => $mat->descricao,
            "descricao_internacional" => $mat->descricao_internacional,
            "assinatura_instrutor" => $mat->assinatura_instrutor,
            "sigla" => $mat->sigla,
            "idmateria" => $mat->idmateria,
            "nome_materia" => $mat->nome_materia,
            "nome_ingles" => $mat->nome_ingles,
            "numero_tempo" => $mat->numero_tempo,
            "carga_horaria" => $mat->carga_horaria,
            "modulo" => $mat->modulo
        );
    }

    print_r(json_encode($data));
    return json_encode($data); //retorna dados do array em json

}
    
asked by anonymous 13.05.2016 / 15:44

1 answer

3

I believe that what you want is to change the ordering and thus change the other sequences avoiding that there are 2 equal values. You may be doing the following!

Let's say you have the following variables:

// array com os valores obtidos
$frutas = array(
    0 => 'maça',
    1 => 'banana',
    2 => 'morango',
    3 => 'melância',
    4 => 'laranja'
);

$maxOrder = count($itens); // 4

Using this function you can change the position without repeating

function sequencia($array, $keyArray, $position)
{
    $i = 0; // valor inicial

    // verifica se a posição que pede é primeira ou última
    switch ($position) {
        case 'first':
            $position = $i;
            break;
        case 'last':
            $position = count($array);
    }

    // reorganiza o array
    foreach ($array as $key => $value) {
        if ($keyArray < $position) {
            if ($key != $keyArray && $key != $position) {
                $result[$i] = $value;
            } elseif ($key == $position) {
                $result[$i] = $array[$key];
            }
        } else {
            if ($key != $keyArray && $key != $position) {
                $result[$i] = $value;
            } elseif ($key == $position) {
                $i++;
                $result[$i] = $value;
            } elseif ($key == $keyArray) {
                $result[$position] = $array[$keyArray];
            }
        }
        $i++;
    }

    return $result;
}

Examples

I want banana to go to position 3 you use

sequencia($frutas, 1, 3);

I want laranja to go to position 1

sequencia($frutas, 4, 1);

You can also be using the arguments first or last for first and last positions

sequencia($frutas, 3, 'first'); // muda posição para primeiro da lista
sequencia($frutas, 2, 'last'); // muda posição para último da lista
  

Editing to adapt with the new addition of the question

I understood what you meant, in case you just add the values of the $result variable to the database.

Example with MySQL:

Before:

$result[$i] = $array[$key];

After:

$conn->prepare("UPDATE tabela SET ordem = $array[$key] WHERE ordem = $i");

I hope you have helped!

    
13.05.2016 / 17:20