如何获取具有正确索引的数据

时间:2017-02-22 11:29:49

标签: php

我遇到了问题,我不确定处理它的最佳方法是什么,因为我没有很多PHP使用经验。

所以我有基本的函数,它返回数据库中的所有项目,看起来像这样。

function getAll($mysqli) {
    $stmt = $mysqli->prepare("SELECT g.id, g.name, g.description FROM control_group as g");

    $stmt->execute();
    $stmt->bind_result($id, $name, $description);
    $groups = array();

    while ($stmt->fetch()) {
        $groups[$id] = array(
            'id' => $id,
            'name' => $name,
            'description' => $description
        );
    }

    $stmt->close();
    $mysqli->close();;
    echo json_encode($groups);
}

该功能会像这样重现响应

5:{id: 5, name: "Group 1", description: null}
11:{id: 11, name: "Group 2", description: null}
14:{id: 14, name: "Group 3", description: null}
17:{id: 17, name: "Group 4", description: null}

我想在这里实现的是像这样的回应

0:{id: 5, name: "Group 1", description: null}
1:{id: 11, name: "Group 2", description: null}
2:{id: 14, name: "Group 3", description: null}
3:{id: 17, name: "Group 4", description: null}

因此,我想要显示正确的索引而不是项目ID,我知道我需要检查索引而不是id,但我不知道如何正确地执行它。

$groups[index] = array(
            'id' => $id,
            'name' => $name,
            'description' => $description
);

2 个答案:

答案 0 :(得分:1)

删除$ id,它将继续添加默认索引。

$i = 0;
while ($stmt->fetch()) {
        $groups[$i] = array(   // Remove $id
            'id' => $id,
            'name' => $name,
            'description' => $description
        );
 $i++;
    }

答案 1 :(得分:1)

$id密钥

中删除$groups
$groups = array();

while ($stmt->fetch()) {
    $groups[] = array(
        'id' => $id,
        'name' => $name,
        'description' => $description
    );
}