dongxi8297 2014-06-03 07:31
浏览 223
已采纳

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

given a very simple table structure thus:

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

which results in an array like this in php (when queried)

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 ) ) 

Am I missing some simple trick to turn this into a simple array with id as the key like so:

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

or is it possible to get PDO to deliver an array like this?

TiA

  • 写回答

3条回答 默认 最新

  • doushan6692 2014-06-03 07:39
    关注

    You can simply use the PDO::FETCH_KEY_PAIR is you have only 2 columns in your result.

    You can also use the PDO::FETCH_GROUP and PDO::FETCH_ASSOC together if you have more. Example :

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

    This will yield an array indexed with the first column containing at each index an array of the result for this key. You can fix this by using array_map('reset', $result) to get your goal.

    Example :

    $result = array_map('reset', $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思