Filter an object array according to field

Asked

Viewed 224 times

0

Doing so:

$total_tipo = $this->chamado->contagem('tipo');

        foreach ($total_tipo as $total_tip){

            print_r($total_tip);
        }

I’m getting this result

stdClass Object
(
    [tipo] => 1
    [quantidade] => 85
)
stdClass Object
(
    [tipo] => 2
    [quantidade] => 492
)
stdClass Object
(
    [tipo] => 3
    [quantidade] => 147
)
stdClass Object
(
    [tipo] => 4
    [quantidade] => 1
)

But what I want is to display the amount of one type, for example:

stdClass Object
(
    [tipo] => 1
    [quantidade] => 85
)

in which case it would only display 85

to display all quantities do this

foreach ($total_tipo as $total_tip => $value){

                print_r($value->quantidade); 

        }

854911471

I can not separate so that comes only quantity of type 1

1 answer

0

Just use the function array_filter to filter by the records you want.

// Busca-se todos os registros
$total_tipo = $this->chamado->contagem('tipo');

// Filtra os do tipo 1
$tipo_1 = array_filter($total_tipo, function ($it) { return $it->tipo == 1; }); 

// Exibe apenas os registros de tipo 1
foreach ($tipo_1 as $value) {
    echo $value->quantidade;
}
  • $tipo_1 = array_filter($total_type, Function ($it) { Return $it->type == 1 }); this line is wrong Message: syntax error, Unexpected '}', expecting ';'

  • @Yes, it is. Can you tell me what it is?

  • Yes had to close the Return, thanks guy worked!

Browser other questions tagged

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