对同一查询结果执行两次不同的提取

I have this query:

$all = $dbh->query("SELECT DISTINCT movimenti.nome, SUM(movimenti_carta.importo)
FROM movimenti_carta JOIN movimenti ON movimenti_carta.movimento=movimenti.id
WHERE month(data)='$mese' AND year(data)='$anno' GROUP BY movimenti.nome");

It retrieves two columns from my db. What I want to do is to put each column in a separate array. If I do:

$labels=$all->fetchAll(PDO::FETCH_COLUMN,0);

I get the values for the first column with the format I am looking for. I tried to do:

$values=$all->fetchAll(PDO::FETCH_COLUMN,1);

after the first fetch but $all is unset by the first fetch and the result is that $values is an empty array (I was pretty sure of this but did give it a try). I can build the arrays in php after I fetch an array with both columns but I was wondering how to get my goal using PDO api.

Of course it will never work this way, as fetchAll() returns data only once.

The only idea I could think of is PDO::FETCH_KEY_PAIR constant:

$data = $all->fetchAll(PDO::FETCH_KEY_PAIR);
$labels = array_keys($data);
$values = array_values($data);

It feels like you are overcomplicating this. It's easily done in PHP, and if you just use PDOStatement::fetch, you don't need to worry about array manipulation; it will also be more friendly to your memory usage if you have a lot of data.

$labels = [];
$values = [];

while ($row = $all->fetch(PDO::FETCH_NUM)) {
    $labels[] = $row[0];
    $values[] = $row[1];
}

Maybe you could use array_column.

$all = $dbh->query("
    SELECT DISTINCT movimenti.nome, SUM(movimenti_carta.importo) AS importo
    FROM movimenti_carta 
    JOIN movimenti ON movimenti_carta.movimento=movimenti.id
    WHERE month(data)='$mese' 
    AND year(data)='$anno' 
    GROUP BY movimenti.nome
");
// set of results indexed by column name
$results = $all->fetchAll(PDO::FETCH_ASSOC);
// set of values from the column 'nome'
$nomes = array_column($results, 'nome');
// set of values from the column 'importo'
$importos = array_column($results, 'importo');