dougai0138 2013-05-29 12:55
浏览 39
已采纳

如何动态地将两个关联值保存到数组中并在js中访问它们?

I'm currently saving $row 'id' from my database into an array. This array is then sent using json_encode back to my JS file, where I access it. This is working fine.

My issue is that I'm struggling to figure out how to add $row['vote_fb_name'] (string) to the same json callback array (in this case my callback is saved into $feedback)? $row['vote_fb_uid'] and $row['vote_fb_name'] appear in the same record.

My PHP - here I save my id's into the array:

while ($row = mysql_fetch_assoc($res))
{
  $savedResultsInNewArray[] = $row['vote_fb_uid'];
}
$feedback = $savedResultsInNewArray;

I then do my callback which is received by my js file:

echo json_encode(array('returned_val' => $feedback));

In my JS I then run a for loop to access the id's:

for( var i = 0; i < data.returned_val.length; i++ ){
  var returnedId = data.returned_val[i];
  console.log("IDS HERE "+returnedId);
}

In this same for loop I'm looking to access the associated 'name'.

In PHP I figure I need to save my data as a two dimensional array, but how do I do that and afterwards how do I access it in my JS?

  • 写回答

3条回答 默认 最新

  • dongyang0005 2013-05-29 13:09
    关注

    Try this method,

    In PHP code

    while ($row = mysql_fetch_assoc($res))
    {
        $feedback[] = array($row['vote_fb_uid'], $row['vote_fb_name']);
    }
    echo json_encode(array('returned_val' => $feedback));
    

    In JS

    for (i in data.returned_val) {
     console.log("IDS HERE "+data.returned_val[i][0]);
     console.log("NAME HERE "+data.returned_val[i][1]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的