【问题标题】:how to loop all data on JSON如何在 JSON 上循环所有数据
【发布时间】:2014-05-14 19:57:18
【问题描述】:

您好,我尝试循环我的json_encode() 以获取所有基于我的查询相关的数据 脚本工作正常,但循环部分不行

这是我目前所拥有的:

$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_GET['rid'], PDO::PARAM_STR);
$stmt6->execute();
    foreach($stmt6->fetchAll()as $res)
        {
            $usern = $res['username'];
            $user_lvl = $res['ulvl'];
        }

$comb = $usern . $_GET['name'];


  $sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids";
  $msg_id = $con4->prepare($sql6);
  $msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
  $msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
  $msg_id->execute();
  $msgd = $msg_id->fetchColumn();
  $tbpre = $msgd;
    $sql7 = "SELECT   message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";

    $stmt7=$con3->prepare($sql7);
    $stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
    $stmt7->execute();



  $message_query = $stmt7;


if(count($message_query) > 0) {
    while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
        echo json_encode($message_array);
    }
}

它只从我的数据库中返回一个数据..

这是我用于从我的 php 端检索的 javascript:

        function AjaxRetrieve()
        {
          var rid = document.getElementById('trg').value,
    data = {chat: uid, rid: rid, name: user};

$.get('includes/getChat.php', data, function (result) {
    var res = $([]);

    $.each(result[0], function(key, value) {
        res = res.add($('<div />', {text : value}));
    });

    $("#clog").html(res);

}, 'json');
        }

【问题讨论】:

  • &那个数据一定是最后一个?
  • $json_string += json_encode($message_array);
  • @DeepakMane 这不是正确的方式
  • 是 $json_string_array[]= ($message_array);最后一行将是 echo json_encode($json_string_array)
  • @DeepakMane 你给的东西没有显示任何东西。这是为什么?

标签: javascript php json while-loop


【解决方案1】:

您只需在每次循环迭代时不断覆盖 $json_string。

您要做的是将数据库数据保存到数组然后编码。

$array = array();
if(count($message_query) > 0) {
    while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
        $array[] = $message_array;   
    }
}
$json_string = json_encode($array);
echo $json_string;

似乎在您的 AJAX 成功处理函数中,您没有正确地迭代数组。

这里注意你只在返回结果集的第一个数组元素上调用$.each()

$.each(result[0], function(key, value) {
    res = res.add($('<div />', {text : value}));
});

我想你会想像这样迭代整个结果集:

$.each(result, function(rowKey, row) {
    // row is single row of result set from database
    // rowKey is numerical index of the row in the result set
    // rowKey is probably not useful here
    // You can just append new div to #clog with
    // whatever content from row which you desire
    // for example, this would insert message_content value
    // in child div to #clog
    $("#clog").append('<div>' + row.message_content + '</div>');
});

【讨论】:

  • 嗨,我试过这段代码,输出是[object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] 知道我错过了什么吗?
  • @user256009 你能说明你的使用情况吗?这看起来像是您尝试 echo 一个对象时会得到的结果,而不是如果您对数组进行 JSON 编码然后回显 JSON 字符串时会得到的结果。
  • 我已经查看了您脚本的响应,它以数组格式显示了一组我从数据库中获取的所有数据。但是它为什么会在我的页面上显示[object Object] =(
  • @user256009 看起来在你的 AJAX 成功处理程序中处理 result 的位置,你只在返回的第一个数组项上调用 $.each() - result[0] 我想你会想要迭代整个结果集。我会用一些额外的评论来更新答案。
  • 你的正确主人@Mike Brant 它给了我所有的消息内容......但这是否意味着我必须添加更多$("#clog").append('&lt;div&gt;' + row.message_content + '&lt;/div&gt;'); 才能根据我的需要显示其他数据?例如,我还需要从我的 json 结果中添加用户名和时间/日期。我需要再添加 2 个吗?
【解决方案2】:

请使用-&gt;rowCount() 计算行数:

$json = array();

if($message_query->rowCount() > 0) {
    while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
        $json[] = $message_array;
    }
}
echo json_encode($json);

您应该使用一个数组来存储您的 message_arrays,这样您就不会一遍又一遍地替换同一个变量。

【讨论】:

  • -&gt;num_rows 可用于 PDO 吗?因为我认为您的代码 sn-p 没有显示任何结果的原因是 -&gt;num_rows 的兼容性我不确定 =)
  • 对不起,我已经更改了我的代码。另外,如果你得到 [object Object],这是来自开发工具还是直接来源?
  • 是的,我已经尝试过它的工作,是的,我从直接来源获得的输出是 [object Object]
  • 请发布您为print_r($json) 而不是echo json_encode($json) 获得的内容。也许数据已经不是您所期望的。
  • 这是 firebug Array([0] =&gt; Array ([0] =&gt; Array ([message_content] =&gt; asdafgga [username] =&gt; ab [message_time] =&gt; 2014-04-03 14:50:03 [recipient] =&gt; cd) 的结果,我已经剪掉了结果,因为它太长了,但这肯定是打印整个数据
【解决方案3】:

试试这个.....

$i=0;
$fet=mysql_query('select * from tbl1 WHERE tbl1.id='20');
while($row=mysql_fetch_assoc($fet,MYSQL_ASSOC)){ 
$json[$i]['date']=$row['time'];
$i++;
} 
echo json_encode($json);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多