Compare two array values with foreach

Asked

Viewed 642 times

-1

I own a Foreach in an array to mount a given table, the array is ordered, but I need to remove duplicated values and leave only some information of it and not all. My idea is to compare the n with n-1 where n is the position of the array, but my doubt is on how to do this with the foreach, with a for until I know how to solve but with foreach perhaps from little experience in language I have not found a way.

The code is that way at the moment

 foreach ($results as $k => $v) {
        $html .= '
        <tr>
        <td>'.$v->nosso_numero.'</td>
        <td>'.$v->ocorrencia.'</td>
        <td>R$'.number_format($v->vlr_boleto, 2, ',', '.').'</td>
        <td>'.$v->matricula.'</td>
        <td>'.$v->nome.'</td>
        <td>'.$v->competencia.'</td>
        <td>R$'.number_format($v->valor_devido, 2, ',', '.').'</td>
        </tr>
';
    }

I’d like to make a comparison if

$results[n]->nosso_numero != $results[n-1]->nosso_numero

And assemble based on this check.

  • Have you tried using array_unique($array) ?

  • array_unique will return me a new array, I need based on my mount.

  • Here’s how you insert some items from your $Results array?

  • A question: is this array generated based on a query in the relational database? An alternative, outside of PHP, would be to use a DISTINCT when selecting the data.

1 answer

1


You have to consider each variable in its foreach. For example:

  • $results : List of results
  • $k : Position of your list (index)
  • $v : Item referring to position

Whereas the first position should not be compared to the previous one, the first condition is whether the index is greater than 1. Thus:

if($k > 1)

The second condition is the comparison with the previous item. Thus:

if($results[$k] !=$results[$k-1])

It is possible to do this in just one if, using the two conditions:

if($k > 1 && $results[$k] !=$results[$k-1])

The final result:

foreach ($results as $k => $v) {        
    if($k > 1 && $results[$k] !=$results[$k-1]){
        echo $v."\n";
    }                
}

Obs.: This way will not remove duplicate items, but rather hide them at the time of viewing.


It is possible to perform this removal procedure using the method array_unique($params), creating a new array from your list of repeated items. See:

$newResults = array_unique($results);

Browser other questions tagged

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