繁体   English   中英

在json_encode中合并多个foreach结果

[英]Combining Multiple foreach Result in json_encode

我正在尝试获取以下json_encode输出:

数组:

echo json_encode(array(
             array(
             'id' => 111,
             'title' => "Event1",
             'start' => "2012-8-10",
             'end' => "2012-8-15",
             'url' => "http://yahoo.com/",
                ),
            array(
             'id' => 222,
             'title' => "Event2",
             'start' => "2012-8-20",
             'end' => "2012-8-22",
             'url' => "http://yahoo.com/"
               )
              ));

输出:

    [{"id":111,"title":"Event1","start":"2012-8-10","end":"2012-8-15","url":"http:\/\/yahoo.com\/"},{"id":222,"title":"Event2","start":"2012-08-20","end":"2012-08-22","url":"http:\/\/yahoo.com\/"}]

但是,当我使用以下代码时

global $wpdb;
$row = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_title FROM $wpdb->posts WHERE $wpdb->posts.post_type = 'calendar' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.post_date ASC");
foreach ($row as $post) {
    $postid = $post->ID;
    $post_title = $post->post_title;
    $startDate =  get_post_meta($post->ID,'calendar_start-date',true);
    $endDate =  get_post_meta($post->ID,'calendar_end-date',true);
    $link =  get_post_meta($post->ID,'calendar_link',true);
    $arr = array('id' => $postid, 'title' => $post_title, 'start' => $startDate, 'end' => $endDate, 'url' => $link);
    echo json_encode($arr);
    }

我得到的输出为

{"id":"320","title":"Test Event One","start":"2012-8-17","end":"2012-8-24","url":"http:\/\/www.yahoo.com"}{"id":"321","title":"Test Event Two","start":"2012-8-21","end":"2012-8-30","url":"http:\/\/www.google.com"}

我了解这可能是由于json_encode位于foreach循环内。 但是,当我在外面尝试时,它只会显示第一个结果。 如何将这些foreach值组合以实现如上所述的输出?

您可以使用此:

global $wpdb;
$posts = array();
$row = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_title FROM $wpdb->posts WHERE $wpdb->posts.post_type = 'calendar' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.post_date ASC");
foreach ($row as $post) {
    $postid = $post->ID;
    $post_title = $post->post_title;
    $startDate =  get_post_meta($post->ID,'calendar_start-date',true);
    $endDate =  get_post_meta($post->ID,'calendar_end-date',true);
    $link =  get_post_meta($post->ID,'calendar_link',true);
    $arr = array('id' => $postid, 'title' => $post_title, 'start' => $startDate, 'end' => $endDate, 'url' => $link);
    $posts[] = $arr;
}
echo json_encode($posts);

我认为应该可以

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM