Scenario
Let's say I have 100 records in any BD .
ID | PESSOA | CARRETO | ENDERECO | DISTANCIA
1 | A | C10 | XX | 20
2 | B | C20 | XY | 25
3 | D | C50 | XZ | 19
4 | D | C50 | XZ | 19
5 | F | C10 | XW | 27
...
...
From a query, I'm going to generate an Array with all these records , and while doing fetch
, I need to check some conditions, comparing the previous record of the current record :
-
ID
of reg. previous=
ID
of reg. current -1 -
PESSOA
of reg. previous=
PESSOA
of reg. current -
CARRETO
of reg. previous=
CARRETO
of reg. current -
ENDERECO
of reg. previous=
ENDERECO
of reg. current -
DISTANCIA
of reg. previous=
DISTANCIA
of reg. current
Example:
ID | PESSOA | CARRETO | ENDERECO | DISTANCIA
3 | D | C50 | XZ | 19
4 | D | C50 | XZ | 19
( If all conditions are true, I write the current record with DISTANCIA = 0
.)
How I did
In the loop I make fetch
, I used auxiliary variables to bring and compare the previous record check the conditions, and write the current one in the array:
// variáveis auxiliares:
$id_ant = null; // seto como null para a 1a comparação
$pes_ant; $car_ant; $end_ant; $dis_ant;
while ($row = $result->fetch_assoc()) {
// verifico as condições
if ($id_ant == $row['ID']-1 && $pes_ant == $row['PESSOA'] && $car_ant == $row['CARRETO'] && $end_ant == $row['ENDERECO'] && $dis_ant == $row['DISTANCIA'])
$row['DISTANCIA'] == 0;
// gravo o registro no array
$array[] = $row;
// seto cada variável para depois utilizar na comparação posterior
$id_ant = $row['ID'];
$pes_ant = $row['PESSOA'];
$car_ant = $row['CARRETO'];
$end_ant = $row['ENDERECO'];
$dis_ant = $row['DISTANCIA'];
}
Example how the 4
register in the array would look like:
(
[ID] => 4
[PESSOA] => D
[CARRETO] => C50
[ENDERECO] => XZ
[DISTANCIA] => 0
)
Questions
- What if I had a table with 100 columns to compare? Would you have to do all this one by one or have an "automatic" way to do this?
- Is it advantageous for me to do this already in
fetch
or would it be better to throw everything into an Array and then work on it? (thinking about performance)