【问题标题】:How to get fetched data with correct index如何获取具有正确索引的数据
【发布时间】:2017-02-22 11:29:49
【问题描述】:

我有问题,我不确定什么是最好的处理方法,因为我没有太多的 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
);

【问题讨论】:

    标签: php


    【解决方案1】:

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

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

    【讨论】:

    • 如果我把那个留空然后在我的用户界面上我不能让这个功能成功输入,当我输入 $groups['id'] 或其他东西时它才有效,有没有办法在这里传递索引而不是将其留空?
    • 初始化 $i = 0;将 $i 放在那里并增加它。
    • 更新我的答案请交叉检查
    • 你好先生,你能看看这个问题stackoverflow.com/questions/42469947/…我试着像你在这里告诉我的那样创建对象,但是你可以看到这个对象更复杂,所以我想知道你能帮我吗这里也 ?提前谢谢
    【解决方案2】:

    $groups 键中删除$id

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2021-07-27
      • 1970-01-01
      • 2018-07-25
      相关资源
      最近更新 更多