MySQL 结果到 PHP 数组

Posted

技术标签:

【中文标题】MySQL 结果到 PHP 数组【英文标题】:MySQL result to a PHP array 【发布时间】:2019-03-13 16:21:43 【问题描述】:

我正在尝试获取这种格式的 json 数组:

var js_array = [
   ["Name1", "Address1", "Url1"],
   ["Name2", "Address2", "Url2"],
   etc...
]

来自 mysql 查询。 这是我的数据库:

+---------+-------------+---------+
|   Name  |   Address   |   URL   |
+---------+-------------+---------+
|  Name1  |  Address1   |   Url1  |
|  Name2  |  Address2   |   Url2  |
|  Name3  |  Address3   |   Url3  |
+---------+-------------+---------+

我试过这个:

$query = $bdd->query('SELECT Name, Adress, URL FROM festivals');
while ($row = $query->fetch()) 
    $array[] = $row['Name'];
    $array[] = $row['Adress'];
    $array[] = $row['URL'];

//Then I return it as an js array that I use later
$js_array = json_encode($array);

结果是:

["Name1", "Address1", "Url1", "Name2", "Address2", "Url2", "Name3", "Address3", "Url3"]

我也试过这个:

$query = $bdd->query('SELECT Name, Adress, URL FROM festivals');
while ($row = $query->fetch()) 
    $array[] = $row;

//Then I return it as an js array that I use later
$js_array = json_encode($array);

返回这个:

[
 0: "Name1", 2: "Address1", 2: "Url1", Name: "Name1", Address: "Address1", URL: "Url1",
 0: "Name2", 2: "Address2", 2: "Url2", Name: "Name2", Address: "Address2", URL: "Url2"
]

有没有办法得到我想要的? 谢谢

【问题讨论】:

【参考方案1】:

你只需要为每一行创建一个数组,其中只有值:

$query = $bdd->query('SELECT Name, Adress, URL FROM festivals');
while ($row = $query->fetch()) 
    $array[] = array($row['Name'], $row['Adress'], $row['URL']);

//Then I return it as an js array that I use later
$js_array = json_encode($array);

【讨论】:

或者你可以做fetchAll(),它做同样的事情。 @Mike OPs 第二个测试用例等同于fetchAll() 并产生错误的结果。参见例如PDOStatement::fetchAll @Nick 这是因为 fetch 样式默认为 PDO::FETCH_BOTH。要获得数字索引,只需执行$query->fetchAll(PDO::FETCH_NUM)

以上是关于MySQL 结果到 PHP 数组的主要内容,如果未能解决你的问题,请参考以下文章

PHP/mysql:使用数组查询 MySQL 并在数组中获取结果

比较 php MySQL 查询结果数组以从其中一个数组中获取关联值

从 MySQL 结果创建 PHP 数组

PHP,MySQL - 结果数组洗牌会比“select ... order by rand()”更快吗?

使用“mysql_fetch_row”从数据库中检索结果并使用 PHP 和 mysqli 插入数组?

MySQL/PHP 输出数组重复查询然后显示结果,如何删除查询? [复制]