控制json feed的输出

时间:2015-05-11 23:01:02

标签: php json wordpress

我正在尝试从Wordpress查询中提取json提要。我需要格式化JSON [{“id”:“1”,“title”:“title”},{“id”:“2”,“title”:“title2”}]

json_encode函数没有提取这种特定的格式:项目没有逗号分隔,我也缺少初始和最终[]

我使这段代码回显了那些缺失的元素,这些元素运行良好,但是最后一个逗号,因为echo使得脚本读取失败。

<?php 
$args = array(
    'post_type' => 'location',
    'posts_per_page' => -1
);

$locations = new WP_Query($args);

    if($locations -> have_posts()):
        echo '[';
        while ($locations->have_posts()) : $locations->the_post();
        $coords = get_field('coordinates');
        $pid = get_the_ID();
        $json["id"] = $pid;
        $json["name"] = get_the_title();
        $json["lat"] = $coords['lat'];
        $json["lng"] = $coords['lng'];
        $json["address"] = get_field('address');
        $json["address2"] = get_field('address_2');
        $json["city"] = get_field('city');
        $json["state"] = get_field('state');
        $json["postal"] = get_field('zip_code');
        $json["phone"] = get_field('office_phone');
        $json["fax"] = get_field('office_fax');
        $json["web"] = apply_filters('the_permalink', get_permalink());      
        echo json_encode($json);
        echo ',';
    endwhile;
        echo ']';
    endif;

?>

我知道回应那些元素并不是正确的方法,而且我在编码上做错了,这就是为什么它没有正确的格式化而退出。

我已经研究了几天,我找不到创建json_encode回显的方法,同时控制它将从wordpress查询中显示的字段。

我提前感谢任何解决方案/导致解决此问题。

1 个答案:

答案 0 :(得分:2)

你在循环中添加错了。你想要做的是创建一个数组,并将该数组显示为json。

if($locations -> have_posts()):
    $data = array();
    while ($locations->have_posts()) : $locations->the_post();

    // add the location stuff to the $data array
    $data[] = array(
        'id' => $pid,
        'name' => get_the_title(),
        // etc....
    );

    endwhile;
// present your json
echo json_encode($data);

endif;