【问题标题】:PHP DBH->fetch() and fetchAll(), there is a way to get rid of "numbered" items in the returned arrays? [duplicate]PHP DBH->fetch() 和 fetchAll(),有没有办法摆脱返回数组中的“编号”项? [复制]
【发布时间】:2015-06-24 00:36:57
【问题描述】:

我从一个 PHP 文档页面复制并粘贴示例,因为情况类似:当我使用 DBH->fetch() 执行 MySQL 查询时,我获得了一个数组:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

输出将是:

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [name] => pear
            [0] => pear
            [colour] => green
            [1] => green
        )

    [1] => Array
        (
            [name] => watermelon
            [0] => watermelon
            [colour] => pink
            [1] => pink
        )
)

有没有办法告诉驱动程序只返回“命名”数组元素并删除带有数字索引的元素?比如:

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [name] => pear
            [colour] => green
        )

    [1] => Array
        (
            [name] => watermelon
            [colour] => pink
        )
)

提前致谢, 西蒙娜

【问题讨论】:

  • 谢谢马里奥,这正是我想要的。

标签: php mysql fetch fetchall


【解决方案1】:

Fetch_Assoc 只返回命名数组。这是您的更改代码。

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetch_assoc();
print_r($result);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 2021-08-27
    • 2011-06-15
    • 2016-03-16
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多