【问题标题】:Returns only one object JSON instead multiple objects PHP? [closed]只返回一个对象JSON而不是多个对象PHP? [关闭]
【发布时间】:2013-07-07 05:25:53
【问题描述】:

首先,请看一下这个 JSON http://ws.luyencong.net/data/search/query.php?do=json

代码如下:

/* --- Execute query and get the data. --- */
$query = $db->query("SELECT t.* FROM ".TABLE_PREFIX."threads t");
while($data = $db->fetch_array($query))
{
    $results[] = array($data['subject'] => $data['subject']);
    $json = json_encode($results, JSON_FORCE_OBJECT);
}

/* --- Print the results to the screen, for future purposes. --- */
echo $json;

但我希望输出的 JSON 格式如下所示:http://ws.luyencong.net/data/search/json.txt

我们将不胜感激。谢谢你。

祝你有美好的一天!

【问题讨论】:

  • 所以你想让我们告诉你用 [] 包装你的 JSON? :)
  • 请包括一个简单的例子:输出现在看起来如何,应该看起来如何。链接的输出不可读。
  • 你想要一个包含 B\u1ed1 c\u00e1o th\u00e0nh l\u1eadp di\u1ec5n \u0111\u00e0n Luy\u1ec7n C\u00f4ng 这样的键的 json 哈希?

标签: php json


【解决方案1】:

我相信你只是想改变这个:

$results[] = array($data['subject'] => $data['subject']);

到这里:

$results[$data['subject']] = $data['subject'];

并且,正如@Orangepill 建议的那样,将您的json_encode 呼叫移出循环。因此,您的整个解决方案将如下所示:

/* --- Execute query and get the data. --- */
$query = $db->query("SELECT t.* FROM ".TABLE_PREFIX."threads t");
$results = array();
while($data = $db->fetch_array($query))
{
    $results[$data['subject']] = $data['subject'];
}

/* --- Print the results to the screen, for future purposes. --- */
echo json_encode($results, JSON_FORCE_OBJECT);

【讨论】:

    【解决方案2】:

    你必须将你的 json_encode 调用移到循环之外。

    /* --- Execute query and get the data. --- */
    $query = $db->query("SELECT t.* FROM ".TABLE_PREFIX."threads t");
    while($data = $db->fetch_array($query))
    {
        $results[$data['subject']] = $data['subject'];
    }
    $json = json_encode($results, JSON_FORCE_OBJECT);
    /* --- Print the results to the screen, for future purposes. --- */
    echo $json;
    

    【讨论】:

    • 但是为什么键和值是一样的呢?不应该是数组('subject'=>$data['subject']);
    • @steven 只有操作人员才能确定..
    • 您的答案没有按照 OP 的要求重新格式化 json。
    • 这将使代码更高效,但由于$json 变量在循环中每次都会被覆盖,最终结果将完全相同。
    • 已更新以根据操作要求重新格式化
    【解决方案3】:

    您正在嵌套数组。看起来您只想拥有一个 JSON 对象而不是它们的数组。因此,将$result 的设置更改为:

    $results[$data['subject']] = $data['subject'];
    

    然后按照建议将json_encode 移出循环,直到填充数组后才需要这样做。您只是无缘无故地一遍又一遍地覆盖变量。

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      相关资源
      最近更新 更多