【问题标题】:Exporting from MySQL to an Object array in PHP and then JavaScript从 MySQL 导出到 PHP 和 JavaScript 中的对象数组
【发布时间】:2018-07-19 21:12:39
【问题描述】:

我有下面的代码将数据从 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

我必须改变什么才能获得预期的结果?

结果只有一个

【问题讨论】:

  • 如果只有一个元素:$profile = array(...?而不是推动这个价值...... $profile[] = array(
  • 除非您删除一些我们看不到的字段,否则您可以直接使用$profile = $row,因为键都是相同的

标签: javascript php mysql arrays


【解决方案1】:

基于这一行:

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】:

    也许这会有所帮助:

    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);
    

    你是在创建一个“对象”,还是一个对象数组?如果是后者,那么您需要以适当的偏移量引用对象。显而易见,希望代码能够使其显而易见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-16
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多