mysqli的json_encode查询奇怪的数组结果

时间:2014-11-18 13:49:18

标签: javascript php mysql json

我想将jql的sql查询结果。因此我找到了许多建议使用json_encode方法的解决方案。我写了这段代码:

$sql = "SELECT idDozent FROM Dozent;";
    $rows = array();
    $result = $con->query($sql);
    while($row = $result->fetch_array()) {
        $rows[] = $row;
    }

现在在我的javascript代码中写道:

var jsonarray = <?php echo json_encode($rows); ?>;

我的表格如下:

idDozent | Name
7        | ...
8        | ...

但是数组包含:

[{"0":"7","idDozent":"7"},{"0":"8","idDozent":"8"}]

我做错了什么?

如何访问阵列的一条记录?

由于

2 个答案:

答案 0 :(得分:0)

使用此:

$rows[$row['idDozent']] = $row['Name'];

当您在代码中使用$rows[] = ...时,php会自动将密钥添加到您的数组中。而不是这个,你可以指定自己的密钥!但是要注意使用重复的密钥。

答案 1 :(得分:0)

javascript数组很好,但是如果你不想在数组中复制(数字和字符串属性名称),那么改变你的mysql查询以返回关联数组:

//while($row = $result->fetch_array()) {
while($row = $result->fetch_assoc()) {
...

var jsonarray = <?php echo json_encode($rows); ?>;
console.log(jsonarray[0].idDozent);

http://php.net/manual/en/mysqli-result.fetch-assoc.php