dow72046 2013-04-30 07:18
浏览 68
已采纳

多维PHP数组到JSON数组

I have this PHP Array:

Array
(
    [messages] => Array
        (
            [0] => Array
                (
                    [sender] => 17
                    [receiver] => 4
                    [message] => TEST 2
                    [timestamp] => 1367200891
                    [read] => 0
                )

            [1] => Array
                (
                    [sender] => 17
                    [receiver] => 4
                    [message] => TEST 1
                    [timestamp] => 1367197661
                    [read] => 0
                )

        )

    [new_messages] => 2
)

It gets retrieved via an Ajax Request, using json_encode() to output it in PHP.

function getMessages(rec){
var nmsg = $.ajax({
        type: "GET",
        async: true,
        url: "/ps/getUserMessages.php",
        data: {'u':rec,'s00':s00,'n01':n01,'t02':t02}       
    });
    nmsg.done(function(data) {
        var json = JSON.parse(data);
        if (typeof json.messages[0].message !== 'undefined') {
            printMessage(json);
        }
    }); 
}

And as printMessage() function, for example, i need to do something like:

loop(){
    $("#elem").append(
          '<div>Sender: '+arrayOfValues.sender+'</div>'
         +'<div>Message: '+arrayOfValues.message+'</div>'
    );
}

for each Array of values.

I tried jQuery $.each() and also for() with some examples i found, but i cannot get to work.

  • 写回答

2条回答 默认 最新

  • duancai1904 2013-04-30 07:22
    关注

    Something like this should work:

    function printMessage(data) {
      for( var i=0; i<data.messages.length; i++ ) {
        $("#elem").append(
            '<div>Sender: ' + data.messages[i].sender + '</div>'
           +'<div>Message: ' + data.messages[i].message+ '</div>'
        );
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?