Return an in_array () true within an SQL result

2

I have a function inside 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");

In this way I want it to bring me the 10 most visited users sorted descendingly. This is what is happening. However, my problem is to check if a certain user code is in the result. I tried this way:

var_dump(in_array(1182652232, $dados_top_visitas));

But in this case I'm returning false , and it should be true because the 1182652232 code is among the 10 query results.

Where am I going wrong in logic?

    
asked by anonymous 26.05.2017 / 17:47

1 answer

3

I believe you should use array_column

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

Try this.

The in_array only checks values that are in the array, but not in the array 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) , it will false .

Using array_column it will create another array, however listing all cod_usuario , so this would become:

[2, 3]

This will work because it will be able to find 3 , as well as 2 .

    
26.05.2017 / 18:35