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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测