2014-05-16 56 views
-1

我正尝试从我的wordpress页面创建自定义json Feed。问题是循环似乎覆盖每个对象,所以它只打印最后一个对象作为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); 

回答

0

$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变量之外,分配被推到这个阵列。希望这可以帮助。

+0

这很好,谢谢你!将尽我所能接受 – user3423384

相关问题