1

Using PHP PDO and psql
My query:

$stmt = $this->pdo->prepare("select distinct extract(year from conclusion) from agreements_register where conclusion is not null");
$stmt->execute();
return $stmt->fetchAll();

it returns this:

[['date_part' => 2021],['date_part' => 2022]]

but I need this:

[2021, 2022]
  • 1
    You will always receive multiple arrays, you can then flatten them to get the desired result. For flattening, see this question: https://stackoverflow.com/questions/14944453/how-can-i-flatten-a-simple-array-without-looping – Rylee Jul 22 '22 at 05:27
  • @Rylee 1. who told you that "You will always receive multiple arrays"? 2. Your question's title is misleading, **nowhere** does if flatten an array "without looping". – Your Common Sense Jul 22 '22 at 05:36
  • @young_protokaa42 but you were asking for the PDO fetch mode, not a post processing? Either way, using Google would have saved a lot of time for the lot of people including yourself – Your Common Sense Jul 22 '22 at 05:38
  • @YourCommonSense calling `fetchAll` returns an **array** which contains each row (as an **array**) hence - "multiple arrays". For the sake of this example, I didn't say "You will receive an array that can contain 0 more arrays which represent each row" as the OP seemed to already understand that. That was also not "my question" - it was a link to one that had a solution to flattening the array. What are you trying to do here? Prove something? – Rylee Jul 22 '22 at 05:47
  • There are also different fetch modes which can return not just array but classes or objects - there's really no need to go into more detail as the answer was based on the context of the question. – Rylee Jul 22 '22 at 05:50
  • @Rylee just to nudge you a bit but nevermind – Your Common Sense Jul 22 '22 at 05:50

1 Answers1

1

this is example:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_COLUMN);
var_dump($result);
?>

and it will output

Array(3)
(
    [0] =>
    string(5) => apple
    [1] =>
    string(4) => pear
    [2] =>
    string(10) => watermelon
)

and detail you can read this doc: https://www.php.net/manual/en/pdostatement.fetchall.php

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345