Compare arrays and highlight changes

Asked

Viewed 38 times

1

I’m having a little problem that I’m having trouble solving. I have an array with a history of occurrences that has 5 positions, and I need to display these histories by highlighting the different items of each array. At the moment I can catch the difference between two of them, but I’m not getting the best way to receive all the differences.

$diff = array_diff($historico[3], $historico[4]);

In this case the histories of position 2,1 and 0 are missing.

The structure of the array I have is this:

[
[0] => Array
    (         
        [0] => 07/06/2018 15:49:00
        [1] => Questionamento :  teste questionamento  
    )
[1] => Array
    (
        [0] => 07/06/2018 15:50:00
        [1] => Questionamento :  teste questionamento 2
    )
 [2] => Array
    (
        [0] => 07/06/2018 15:51:00
        [1] => Questionamento :  teste questionamento 3
    )
 [3] => Array
    (
        [0] => 07/06/2018 15:52:00
        [1] => Questionamento :  teste questionamento 4
    )
  [4] => Array
    (
        [0] => 07/06/2018 15:53:00
        [1] => Questionamento :  teste questionamento 5
    )

]

  • is array within array?

  • Type inside the historical array has 5 arrays?

  • Yes is a history array with an array for each update.

  • I imagine you’ll have to make a recursive loop, taking each and comparing with the rest

  • Only you put the other arrays in there, $diff = array_diff($historico[0],$historico[1],$historico[2],$historico[3],$historico[4]);

  • @Anderson Henrique that way didn’t work.

  • @Marcelo I have to compare the last with the penultimate, the penultimate with the penultimate, until I arrive at the first.

  • You can sort the array before it stops, https://secure.php.net/manual/en/array.sorting.php

Show 3 more comments

1 answer

1


I don’t know why, but if you want to take it backwards do so

#array para pegar as diferenças
$diferencas = array();
#for pegando o tamanho do array e diminuindo, o motivo do menos 1 é que o array inicia de 0 então mesmo tendo 4 registros seriam de 0 a 3 no caso 3, teria que diminuir 1
for($i = sizeof($historico) - 1; $i > 0; $i--):
    #adiciona a comparacao de array da posicao atual com uma anterior
    array_push($diferencas,array_diff($historico[$i],$historico[$i - 1]));
endfor;
#printa as diferencas
print_r($diferencas);

You can also have another form without needing the least

 #array para pegar as diferenças
$diferencas = array();
#Reverte as posicoes dos arrays de tras pra frente, ultimas chaves viram primeiras
krsort($historico);
for($i=0; $i < sizeof($historico) - 1; $i++):
array_push($diferencas,array_diff($historico[$i],$historico[$i + 1]));  
endfor;
print_r($diferencas);
  • Thank you, that way it worked properly.

  • Denada, if I may please mark as an answer I thank you. @Valdirsilva

Browser other questions tagged

You are not signed in. Login or sign up in order to post.