【问题标题】:JSON only prints last object in arrayJSON 只打印数组中的最后一个对象
【发布时间】:2014-05-16 12:52:59
【问题描述】:

我正在尝试从我的 wordpress 页面制作自定义 json 提要。问题是循环似乎覆盖了每个对象,所以它只将最后一个对象打印为 json。我也试过在循环内移动回声,但它看起来可能在浏览器中没有格式化。

这是我的代码:

foreach ($posts as $post) {

    $r = str_replace("\n",'', shorten_txt($post->post_content, 500));
    $n = str_replace("\r", '', $r);
    $post_data = array(
    'title' => get_the_title($post->ID),
    'link' => get_permalink($post->ID),
    'image' => catch_that_image(),
    'content' => $n,
    'time' => strtotime($post->post_date_gmt));

     $data = (array('item' => $post_data));



}

echo json_encode($data);

【问题讨论】:

    标签: php json wordpress


    【解决方案1】:

    $data 的声明发生在 foreach 中,这意味着每次分配值时都会重新初始化它。我不确定您是否错误地执行了此操作,或者您不确定如何执行此操作。

    试试这个

    $data = array();
    foreach ($posts as $post) {
        $r = str_replace("\n",'', shorten_txt($post->post_content, 500));
        $n = str_replace("\r", '', $r);
        $post_data = array(
        'title' => get_the_title($post->ID),
        'link' => get_permalink($post->ID),
        'image' => catch_that_image(),
        'content' => $n,
        'time' => strtotime($post->post_date_gmt));
         $data[] = (array('item' => $post_data));
    
    }
    echo json_encode($data);
    

    它的作用是在foreach 循环之外声明$data 变量,并将赋值推到这个数组中。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多