我使用下面的代码将数据从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
我必须改变什么才能得到想要的结果?
只有一个结果
发布于 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 *
。)
发布于 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);
你是在创建一个“对象”,还是一个对象数组?如果是后者,则需要在适当的偏移量处引用对象。显而易见的声明,希望代码能让它变得明显。
https://stackoverflow.com/questions/51431794
复制相似问题