【问题标题】:How do I use a php array within an array returned to Javascript?如何在返回给 Javascript 的数组中使用 php 数组?
【发布时间】:2015-07-02 19:24:15
【问题描述】:

我已经花了半天多的时间试图找出这个问题,我发誓我已经尝试了所有可能的事情。所以这就是我想要做的事情背后的想法......每10秒Javascript执行一次AJAX调用以查看您是否有在线朋友,然后返回用户列表,他们的状态等......而不是格式化所有内容PHP,出于各种原因,我将使用 Javascript 对其进行格式化......所以这就是发生的事情:

Javascript // 让我们从控制器中获取数据

 $.post('/pagething', { datastuff }, function(data){
 if(data.status == 'ok'){

 // Magic nonsense here that can translate the array example:
 var keys = Object.keys(data.allfriends);

   }
 } etc...

PHP // 让我们跳过控制器中的其他代码,专注于重要的东西

 $friends_information = array(
 'userid' => array();
 'username' => array();
 'avatar' => array();
 'status' => array();
 );

 foreach($result_from_my_friends_model as $row){
 // For ease of read, i'll just associate things with $row

 $friends_information["userid"][] = $row->user_id;
 $friends_information["username"][] = $row->username;
 $friends_information["avatar"][] = $row->avatar;
 $friends_information["status"][] = $row->status;
 }

 $result = array('status' => 'ok', 'allfriends' => $friends_information);
 return json_encode($result);
 exit();

我得到的最接近的方法是通过用户名或用户 ID(例如通过新对象)获取结果,或者获取整个结果但无法区分键,因为例如 object[0][1] 会返回未定义。

先谢谢你,这东西很难理解:/

【问题讨论】:

  • 如果您不为每列创建单独的数组,而是将其作为 $friends_informationp[] = $row;
  • 谢谢,我不知道你可以这样做。我现在就试一试,我们会看看情况如何。 :)
  • 你甚至不需要这样做,因为原来的$result_from_my_friends_model 已经是一个这样组织的数组。看我的回答。

标签: javascript php jquery arrays ajax


【解决方案1】:

没有必要将每一列放入$friend_array 的单独元素中,如果将与特定朋友相关的所有数据放在一个对象中,事情通常会更容易。这样做:

$result = array('status' => 'ok', 'allfriends' => $result_from_my_friends_model);
echo json_encode($result);

在 Javascript 中,确保指定结果为 JSON:

$.post('/pagething', { datastuff }, function(data) {
    if (data.status == 'ok') {
        $.each(data.allfriends, function(i, friend) {
            // do stuff with friend.userid, friend.username, friend.avator, friend.status
        });
    }
}, 'json');

【讨论】:

  • 太棒了!我假设我,朋友以朋友的名义声明了一个新的对象实例?它工作得很好,我把它切换到一个更简单的数组,所以我使用了friend[0]。我会查找 .each 以获取更多信息。非常感谢!
  • i, friend 是回调的参数。 ifriend 是数组元素在数组中循环时的索引和元素。阅读$.each的文档:api.jquery.com/jquery.each
【解决方案2】:

您的keysjs 变量中已经有您的list_of_friend。只需遍历它,您就会得到您想要的结果。祝你好运

【讨论】:

    猜你喜欢
    • 2013-01-12
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2016-02-16
    • 2012-02-15
    相关资源
    最近更新 更多