【问题标题】:Unable to understand the structure of the array无法理解数组的结构
【发布时间】:2018-04-19 14:05:07
【问题描述】:

我在 PostgreSQL/PostGIS 数据库中有一个表,我想在 php 中检索列名及其值以将它们加载到 jquery-datatable 中。当我在$row=$query->fetchAll() 之后print_r($row) 时,我可以看到 print_r 的输出为:

           Array ( [0] => Array ( [d_id] => 20160317 [0] => 20160317 [lid] => 1 [1] => 1 [la_val] => 23.094123 [2] => 23.094123 [lo_val] => 37.607672 [3] => 37.607672 [ctime] => 15:10 [4] => 15:10 [tmp_c] => 28.2 [5] => 28.2 [colour] => 90 [6] => 90). 

我已经能够使用以下方法检索列名:

    $query = $conn->prepare("SELECT * FROM tablename");
    $query->execute();
    $row=$query->fetchAll();
    print_r($row);

    for ($i = 0; $i < $query->columnCount(); $i++) {
        $col = $query->getColumnMeta($i);
        $columns[] = $col['name'];
        print_r($columns[$i]." "); // d_id lid la_val lo_val

但更进一步,我无法理解数组结构。

【问题讨论】:

  • print_r()之前添加echo '&lt;pre&gt;';
  • 哦,太好了。谢谢:)

标签: php arrays postgresql


【解决方案1】:

数组是二维的。外部数组有一个数字索引,表示记录(如您所说的fetchAll(),您可以获得多行)。内部数组实际上是两种的组合:一种使用列号作为键,另一种使用列名。这是因为fetch()fetchAll() 的默认选项是PDO::FETCH_BOTH,相当于PDO::FETCH_NUM | PDO::FETCH_ASSOC。因此,您可以使用不同的数组键获得每列值两次。

【讨论】:

  • 感谢您的解释。我可以查看数组并了解更多信息。但是是否有可能只取回一次数据,使用 1 个键值对,而不是使用不同的数组键查看两次?
  • 是的,使用fetchAll(PDO::FETCH_ASSOC)
  • 非常感谢您的快速帮助。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多