简体   繁体   English

在使用 PDO 的结果中使用列的值作为索引

[英]Using value of a column as index in results using PDO

I have an SQL table called 'brands' with the columns id, name, url.我有一个名为“brands”的 SQL 表,其中包含 id、name、url 列。 In that table I have this data set:在那个表中,我有这个数据集:

1, Solidfloor, solidfloor;
2, Quickstep, quickstep;
4, Cleanfloor, cleanfloor;
5, Blue Dolphin, blue-dolphin;
6, Krono, krono;
8, Meister, meister;

I'm fetching them all right now and I get a nice array in return, but, I need the index of the arrays to not be an incremented number, but the id of that particular row.我现在正在获取它们,并得到一个不错的数组作为回报,但是,我需要数组的索引不是递增的数字,而是该特定行的 id。 I could of course loop through the result set, but is there a cleaner way of doing this?我当然可以遍历结果集,但是有没有更简洁的方法来做到这一点?

Although PDO::FETCH_UNIQUE description in PHP manual is quite unclear, but in fact it's exact parameter you actually need .尽管 PHP 手册中的PDO::FETCH_UNIQUE描述相当不清楚,但实际上它是您实际需要确切参数

$data = $pdo->query('SELECT * FROM table')->fetchAll(PDO::FETCH_UNIQUE);

is giving you an array indexed by the field listed in SELECT clause first (when * is used then first field in the table definition, which should be id in your case).首先为您提供一个由 SELECT 子句中列出的字段索引的数组(当使用 * 时,然后是表定义中的第一个字段,在您的情况下应该是 id )。

Note that by default using just PDO::FETCH_UNIQUE will give you resulting rows with doubled values.请注意,默认情况下,仅使用PDO::FETCH_UNIQUE将为您提供具有双倍值的结果行。 You can either add preferred row mode to this call or - better, set it once for all PDO calls in constructor or via setAttribute() .您可以为此调用添加首选行模式,或者 - 更好的是,在构造函数中或通过setAttribute()为所有 PDO 调用设置一次。 The output below is shown for PDO::FETCH_ASSOC set as default fetch mode.以下输出显示为PDO::FETCH_ASSOC设置为默认获取模式。

  1 => array (
    'name' => 'Solidfloor',
    'url' => 'solidfloor',
  ),
  2 => array (
    'name' => 'Quickstep',
    'url' => 'quickstep',
  ),
  4 => array (
    'name' => 'Cleanfloor',
    'url' => 'cleanfloor',
  ),
)

Fetch as assoc作为关联获取

For the manual: http://php.net/manual/en/pdostatement.fetchall.php对于手册: http : //php.net/manual/en/pdostatement.fetchall.php

fetch_style fetch_style

Controls the contents of the returned array as documented in PDOStatement::fetch().控制返回数组的内容,如 PDOStatement::fetch() 中所述。 Defaults to value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH)默认为 PDO::ATTR_DEFAULT_FETCH_MODE 的值(默认为 PDO::FETCH_BOTH)

To return an array consisting of all values of a single column from the result set, specify PDO::FETCH_COLUMN.要从结果集中返回由单个列的所有值组成的数组,请指定 PDO::FETCH_COLUMN。 You can specify which column you want with the column-index parameter.您可以使用 column-index 参数指定所需的列。

To fetch only the unique values of a single column from the result set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE.要仅从结果集中获取单个列的唯一值,请使用 PDO::FETCH_UNIQUE 按位或 PDO::FETCH_COLUMN。

To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.要返回按指定列的值分组的关联数组,请按位或 PDO::FETCH_COLUMN 与 PDO::FETCH_GROUP。

That last bit is key.最后一点是关键。 It doesn't seem to be completely documented (that I could find), but instead of PDO::FETCH_COLUMN, you can combine PDO::FETCH_ASSOC with PDO::FETCH_GROUP to achieve the desired result:它似乎没有完全记录(我可以找到),但您可以将 PDO::FETCH_ASSOC 与 PDO::FETCH_GROUP 结合使用,而不是 PDO::FETCH_COLUMN 来实现所需的结果:

$PDOstmt->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP)

So, given the above data:因此,鉴于上述数据:

$stmt = $PDO_obj->prepare('select * from brands');
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP);
d($result);

Results in:结果是:

array (6) [
    '1' => array (1) [
        array (2) [
            'name' => string (10) "Solidfloor"
            'url' => string (10) "solidfloor"
        ]
    ]
    '2' => array (1) [
        array (2) [
            'name' => string (9) "Quickstep"
            'url' => string (9) "quickstep"
        ]
    ]
    '4' => array (1) [
        array (2) [
            'name' => string (10) "Cleanfloor"
            'url' => string (10) "cleanfloor"
        ]
    ]
    '5' => array (1) [
        array (2) [
            'name' => string (12) "Blue Dolphin"
            'url' => string (12) "blue-dolphin"
        ]
    ]
    '6' => array (1) [
        array (2) [
            'name' => string (5) "Krono"
            'url' => string (5) "krono"
        ]
    ]
    '8' => array (1) [
        array (2) [
            'name' => string (7) "Meister"
            'url' => string (7) "meister"
        ]
    ]
]

( d() is just a handy debugging function from the kint library, like var_dump() or print_r() ) ( d() 只是来自kint 库的一个方便的调试函数,如 var_dump() 或 print_r() )

Note that the column used to index the array will always be the first column in the results, so you can modify your select statement to choose which column you want.请注意,用于索引数组的列将始终是结果中的第一列,因此您可以修改 select 语句以选择所需的列。 And note also that the indexed column will be stripped out of each row's array;还要注意,索引列将从每一行的数组中删除; to get around that, you can add the column twice to your select statement (ie, select id, brands.* from brands , etc.).为了解决这个问题,您可以将该列两次添加到您的选择语句中(即select id, brands.* from brands等)。

There are more parameters documented here: http://php.net/manual/en/pdostatement.fetch.php , like PDO::FETCH_UNIQUE to make sure that each index is used only once.此处记录了更多参数: http ://php.net/manual/en/pdostatement.fetch.php ,例如 PDO::FETCH_UNIQUE 以确保每个索引仅使用一次。

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

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