donglian1982 2016-03-30 09:56
浏览 184
已采纳

如何从mySQL数据库创建一个数组?

$sql = "SELECT name FROM people WHERE id = '$id'";  
$array = array();       
$q = $pdo->prepare($sql);
$q->execute();
foreach ($pdo->query($sql) as $row) {
$array[] = $row;
}

My result is:

array(4) {
  [0]=>
  array(2) {
    ["name"]=>
    string(4) "fred"
    [0]=>
    string(4) "fred"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(3) "sam"
    [0]=>
    string(3) "sam"
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(4) "alan"
    [0]=>
    string(4) "alan"
  }
  [3]=>
  array(2) {
    ["name"]=>
    string(63) "john"
    [0]=>
    string(63) "john"
  }
}

But I would need:

Array
(
    [fred] => fred
    [sam] => sam
    [alan] => alan
    [john] => john
)

I tried for example:

foreach ($pdo->query($sql) as $key => $row) {..

and also

foreach ($pdo->query($sql) as $row) {
$array[] = $row;
$row = array_combine(array_values($row), array_values($row));
}

but I always get the same result...

  • 写回答

3条回答 默认 最新

  • dousuochu7291 2016-03-30 10:33
    关注

    Use fetchAll()

    But not a vanilla one but with a secret argument called PDO::FETCH_COLUMN

    $sql = "SELECT name FROM people WHERE id = ?";  
    $q = $pdo->prepare($sql);
    $q->execute([$id]);
    $array = $q->fetchAll(PDO::FETCH_COLUMN);
    

    It will get you a single-dimensional array with names like this

    Array
    (
        [0] => fred
        [1] => sam
        [2] => alan
        [3] => john
    ) 
    

    Note that you are using prepared statements completely wrong way making your code vulnerable to SQL injection. It is fixed in the code above.

    If you insists on getting both key and value, then change your code as follows

    $sql = "SELECT name, name FROM people WHERE id = ?";  
    $q = $pdo->prepare($sql);
    $q->execute([$id]);
    $array = $q->fetchAll(PDO::FETCH_KEY_PAIR);
    

    and it will give you exact array as you asked

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 yolov5中的val测试集训练时数量变小问题
  • ¥15 MPLS/VPN实验中MPLS的配置问题
  • ¥15 materialstudio氢键计算问题
  • ¥15 已知隐函数其中一个变量的,求另外一个变量
  • ¥15 echarts图表制作
  • ¥15 halcon根据玻璃面板纹路取区域
  • ¥15 HFSS设计小型化180度耦合器
  • ¥15 使用CInternetSession,CHttpFile读取网页文件时有些电脑上会卡住怎么办?
  • ¥15 水下机器人的半物理仿真研究
  • ¥15 微服务假死,一段时间后自动恢复,如何排查处理