php(PDO)将查找表中的行转换为简单数组的简单方法

时间:2014-06-03 07:31:28

标签: php mysql sql arrays pdo

给出一个非常简单的表结构:

mysql> describe songpart;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| id       | int(11) | NO   | MUL | NULL    | auto_increment |
| partName | text    | NO   |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+

导致php中的数组(查询时)

Array ( [0] => Array ( [id] => 1 [0] => 1 [partName] => Lead Guitar [1] => Lead Guitar ) 
        [1] => Array ( [id] => 2 [0] => 2 [partName] => Bass Guitar [1] => Bass Guitar ) 
        [2] => Array ( [id] => 3 [0] => 3 [partName] => Drums [1] => Drums ) 
        [3] => Array ( [id] => 4 [0] => 4 [partName] => Keyboard [1] => Keyboard ) ) 

我错过了一些简单的技巧,将其转换为一个简单的数组,其中id为关键字,如下所示:

Array ( [1] => Lead Guitar
        [2] => Bass Guitar
        [3] => Drums
        [4] => Keyboard )

或者是否可以让PDO提供这样的数组?

TIA

3 个答案:

答案 0 :(得分:5)

您只需使用PDO::FETCH_KEY_PAIR,结果中只有2列。

如果您有更多内容,也可以同时使用PDO::FETCH_GROUPPDO::FETCH_ASSOC。示例:

$result = $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

这将产生一个索引的数组,第一列包含每个索引的一个该键的结果数组。您可以使用array_map('reset', $result)来解决此问题。

示例:

$result = array_map('reset', $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));

答案 1 :(得分:3)

试试这个:

$records = $pdo->query('SELECT id, partName FROM myTable');
$records->setFetchMode(PDO::FETCH_KEY_PAIR);
print_r($records->fetchAll());

答案 2 :(得分:0)

为此,您需要在迭代中仅设置所需的字段。

$part_name = [];

$records = $pdo->query('SELECT * FROM your_table');
foreach ($records as $row) {
    $part_name[$row['id']] = $row['partName'];
}