mysql结果到php数组

cx6n0qe3  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(267)

我正在尝试获取以下格式的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"}
]

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

kmpatx3s

kmpatx3s1#

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

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

相关问题