Return an in_array() true within an SQL result

Asked

Viewed 70 times

2

I have a function within the class UsuarioVisitas:

// Retorna o array com os mais visitados
public function CS_GetMaisVisitados($sql_aux)
{
    global $objConexao;

    $strSql =  "SELECT cod_usuario, SUM(count_view) AS total_visitas 
                FROM usuario_visitas
                $sql_aux";  

    $vetDados = $objConexao->query($strSql)->fetchAll();
    return $vetDados;
}

I call the function on another page:

$dados_top_visitas = UsuarioVisitas::CS_GetMaisVisitados("GROUP BY cod_usuario ORDER BY total_visitas DESC LIMIT 10");

So I want him to bring me the 10 most visited users sorted down. That’s what’s going on. However, my problem is to check if certain user code is in the result. I tried this way:

var_dump(in_array(1182652232, $dados_top_visitas));

But in this case it’s returning to me false, whereas it should be true for the code 1182652232 is among the 10 query results.

Where I’m going wrong in logic?

1 answer

3


I believe you should use the array_column

var_dump(in_array(1182652232, array_column($dados_top_visitas, 'cod_usuario')));

Test this.


The in_array only checks values that are in the array, but not in the array within the array, so:

$dados_top_visitas = [
    [
        'cod_usuario' => 2,
        'total_visitas' => 1,
    ],
    [
        'cod_usuario' => 3,
        'total_visitas' => 1,
    ]
];

If you make a in_array(2, $dados_top_visitas), will be false.

Using the array_column it will create another array, but listing all cod_usuario, so that would be:

[2, 3]

That’ll work, because he’ll be able to find the 3, as well as the 2.

  • Perfect @Inkeliz worked exactly as I wanted. Thank you for the time!

Browser other questions tagged

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