Array of unique values with foreach

1

I have the following foreach to get 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 were measured with the same device, I get this value 2 times. How do I do that does not happen?

I'm getting this way:

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

I need to receive this, without repeating:

array:2 [▼
  0 => 1
  1 => 2
]
    
asked by anonymous 11.05.2016 / 19:43

2 answers

2

Have you tried array_unique ? It gets the argument array and returns a new array with no duplicate 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

    
11.05.2016 / 19:50
0

Dude, if it's just the value you need, you can set the indexes of your array to the values of id's received. Php overrides all indexes that are the same, so you only have one index that represents your device ids.

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