Array of unique values with foreach

Asked

Viewed 860 times

1

I got the following foreach to pick up the id of the devices that were used in each sector:

@foreach($relatorio->Empresa->SetorEmpresa as $setor)
   {{ $collection[] = $setor->SetorEmpresaEdificacao->id_aparelho_ruido }}
@endforeach

The problem is that when 2 sectors have been measured with the same device, I get that value 2 times. How do I make it not happen?

I’m getting it like this:

array:3 [▼
  0 => 1
  1 => 1
  2 => 2
]

I need to receive like this, without repeating:

array:2 [▼
  0 => 1
  1 => 2
]

2 answers

2

Have you tried the array_unique? He gets the argument array and returns a new array with no duplicated values.

<?php
$input = array("a" => "verde", "vermelho", "b" => "verde", "azul", "vermelho");
$result = array_unique($input);
print_r($result);
?>

The above example will print:

Array
(
    [a] => verde
    [0] => vermelho
    [1] => azul

)

Source: php.net

  • I even read about this unique array, but I couldn’t apply it. Applying this way doesn’t work, because I don’t pass the array there, but an integer.

  • How is this array? Where is it being defined?

  • she is raised there msm in foreach. $Collection[] = ...

  • got... put $Collection = array_unique($Collection) after foreach

  • Good man, that’s it!

0

Dude, if it’s just the value you need, you can set the indexes of your array with the incoming id values. php overwrites all indexes that are equal, so you will only have a single index that represents your device id’s.

@foreach($relatorio->Empresa->SetorEmpresa as $setor)
   {{ $collection[$setor->SetorEmpresaEdificacao->id_aparelho_ruido] = $setor->SetorEmpresaEdificacao->id_aparelho_ruido }}
@endforeach

Browser other questions tagged

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