简体   繁体   English

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

[英]perform two different fetch on the same query result

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). 在第一次获取之后,但是第一次获取未设置$all ,结果是$values是一个空数组(我很确定这一点,但是尝试了一下)。 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. 在获取包含两列的数组后,可以在php中构建数组,但我想知道如何使用PDO api实现目标。

Of course it will never work this way, as fetchAll() returns data only once. 当然,它将永远不会以这种方式工作,因为fetchAll()仅返回一次数据。

The only idea I could think of is PDO::FETCH_KEY_PAIR constant: 我唯一能想到的想法是PDO :: FETCH_KEY_PAIR常量:

$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; 这在PHP中很容易完成,如果只使用PDOStatement::fetch ,则无需担心数组操作; 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 . 也许您可以使用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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM