首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >先从MySQL导出到对象数组,然后再导出到JavaScript

先从MySQL导出到对象数组,然后再导出到JavaScript
EN

Stack Overflow用户
提问于 2018-07-20 05:12:39
回答 2查看 65关注 0票数 0

我使用下面的代码将数据从MySQL传递到PHP数组:

while ( $row = $result->fetch_assoc() ) {
    $profile[] = array(
        "id" => $row[ "id" ],
        "first" => $row[ "first" ],
        "last" => $row[ "last" ],
        "cell" => $row[ "cell" ],
        "email" => $row[ "email" ],
        "kids" => $row[ "kids" ]
    );
}

然后,我将其编码成JavaScript,如下所示:

var userprofile = <?php echo json_encode($profile); ?>;

它的输出是

要获得一个参数,我必须执行userprofile[0].cell,因为我只想执行userprofile.cell

我必须改变什么才能得到想要的结果?

只有一个结果

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-20 05:21:19

基于这一行:

var userprofile = <?php echo json_encode($profile); ?>;

看起来您已经运行了一个查询来获取包含单个用户的配置文件数据的一行。

但是你获取它的方式

while ( $row = $result->fetch_assoc() ) {
    $profile[] = array(...

如果您想要返回多个用户配置文件,您将如何设置它。

我认为你需要的只是:

$profile = $result->fetch_assoc();

如果配置文件中有您不想发送的其他列,则只需在查询中指定所需的列即可。(用SELECT id, first, last, etc.代替SELECT *。)

票数 2
EN

Stack Overflow用户

发布于 2018-07-20 05:21:29

也许这会有所帮助:

var single = {"foo": 1, "bar": 2};
//PHP would be array('foo' => 1, 'bar' => 2);

var list = [{"foo": 1, "bar": 2}];
//PHP would be array(array('foo' => 1, 'bar' => 2)); ... what you do with []... array_push.

console.log(list[0].foo);

console.log(single.foo);

你是在创建一个“对象”,还是一个对象数组?如果是后者,则需要在适当的偏移量处引用对象。显而易见的声明,希望代码能让它变得明显。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51431794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档