PDO关联数组 - 返回关联

时间:2013-03-20 00:04:30

标签: arrays pdo associative

我有这段代码:

$dbInstance = DB_Instance::getDBO();
$statement = $dbInstance->prepare("SELECT id, name FROM language ORDER BY id");
$statement->execute();      
$rows = $statement->fetchAll(); 

//Create associative array wuth id set as an index in array
$languages = array();
foreach($rows as $r) {
    $languages[$r['id']] = $r['name'];
}
return $languages;

我无法弄清楚如何使用PDO语句来实现数组$ languages产生的相同结果。我尝试了一些不同的fetch_styles。

我尝试了一些不同的风格,我可以这样:

[0] svenska
[1] engelska

但我想要:

[1] svenska
[2] engelska

(其中1和2是数据库中id的值)

我想我可以创建一个函数并用FETCH_FUNC调用它,但我不确定它会如此之大。

以上是最好/最干净的方法吗?

4 个答案:

答案 0 :(得分:16)

每个人都忘记了

$sth->fetchAll(PDO::FETCH_KEY_PAIR);

答案 1 :(得分:11)

不确定是否有更好的方法。你可以尝试一下吗?

$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

$languages = array();

function getLangs($col, $row) {
     $languages[$col['id']] = $col['name'];
}

array_walk($rows, 'getLangs');

foreach循环没有错。我实际上用你所拥有的。要比那更清洁......

<强>更新

在仔细阅读了您的问题后,您真正要问的是,您是否可以格式化QUERY,以便以不同的格式返回结果。

返回普通SELECT查询的方式是:

+----+----------+
| id |     name |
+----+----------+
|  1 |  svenska |
|  2 | engelska |
| .. |      ... |
| .. |      ... |
+----+----------+

$row = array(
    row_1 => array(
        id   => "1",
        name => "svenska"
    ),
    row_2 => array(
        id   => "2",
        name => "engelska"
    ),
    row_3 => array(
        id   => "...",
        name => "..."
    ),
    row_4 => array(
        id   => "...",
        name => "..."
    )
)

$row[$row_number][$column_name] = $value

您要求的是以某种方式返回您的查询结果,如:

// Query result is only one row, with each 'id' as column name
// And the 'name' from the same row as it's value...

+---------+----------+-----+-----+-----+
|       1 |        2 | ... | ... | ... |
+---------+----------+-----+-----+-----+
| svenska | engelska | ... | ... | ... |
+---------+----------+-----+-----+-----+

$row = array(
    row_1 => array(
          1 => "svenska",
          2 => "engelska",
        ... => "...",
        ... => "...",
        ... => "..."
    )
)

$languages = $row[row_1];
$languages[$id] = $name;

我不完全确定你能在SQL中do this完全诚实。我也建议反对它,即使你可以。对于缩放表来说,这将是可怕的。如果你的表是静态的,那么为什么不按照我刚开始提到的方式对其进行格式化呢?为什么不将它放在包含文件中的静态PHP数组中呢?

答案 2 :(得分:8)

我认为您可能正在寻找$result = $sth->fetch(PDO::FETCH_ASSOC);

参考:http://php.net/manual/en/pdostatement.fetch.php

[edit] oops to late:)

答案 3 :(得分:0)

condition {
    path_pattern {
      values = ["/login", "/logout"]
    }
}
condition {
    host_header {
      values = ["my-service.*.terraform.io"]
    }
  }

<?php $dbhost = 'somehost'; $dbuser = 'someuser'; $dbpw = 'somepw'; $dbname = 'somename'; $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,]; $dsn = "mysql:host=$dbhost;dbname=$dbname;"; $pdo = new PDO($dsn, $dbuser, $dbpw, $options); $data = $pdo->query("SELECT * FROM language")->fetchAll(\PDO::FETCH_UNIQUE); var_dump($data); 可以解决问题...