Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php WordPress帖子的输出JSON_Php_Json_Wordpress - Fatal编程技术网

Php WordPress帖子的输出JSON

Php WordPress帖子的输出JSON,php,json,wordpress,Php,Json,Wordpress,我正在使用WordPress插件,我正在创建一个自定义控制器,它返回一个帖子类型的帖子列表。我想要的输出如下: [{ "id": 1, "title": "Sample Post Title" }, { "id": 2, "title": "Sample Post Title" }, .... ] 这是我的自定义控制器: class JSON_API_Custom_Controller { public function get_posts_type() {

我正在使用WordPress插件,我正在创建一个自定义控制器,它返回一个帖子类型的帖子列表。我想要的输出如下:

[{
    "id": 1,
    "title": "Sample Post Title"
},
{
    "id": 2,
    "title": "Sample Post Title"
},
....
]
这是我的自定义控制器:

class JSON_API_Custom_Controller {

 public function get_posts_type() {
    global $json_api;

    $posts_all     = array();

    $args = array( 'post_type' => 'shopping', 'posts_per_page' => -1);
    $loop = new WP_Query( $args );
    if ( $loop->have_posts() ) {
      while ( $loop->have_posts() ) : $loop->the_post();
        $post_id = get_the_ID();
        $post_title = get_the_title($post_id);

        $posts_all []= array(
         'id' => $post_id,
         'title' => $post_title
        );

      endwhile;
    }

   return $posts_all;

  }

}
但结果是:

{  
   "status":"ok",
   "0":{  
      "id":1,
      "title":"sample title"
   },
   "1":{  
      "id":2,
      "title":"sample title"
   }
}

如何输出json对象数组,使之与所需的输出一致?

我认为向json响应添加
状态:ok
是插件的一项功能

因此,您可以修改函数以返回一个带有一个键的数组:

// not this 
//return $posts_all;

// but this
return array('posts' => $posts_all);
在这之后,json响应中仍然有
status
键,但也有
posts
键,您可以对其进行迭代

更新: 我想,过滤器
json\u api\u encode
可能会对您有所帮助。您可以取消设置
状态
键:

add_filter('json_api_encode', 'remove_status');

function remove_status($response) {
    unset($response['status']);

    return $response;
}

希望下面的代码能为您做到这一点

 return json_encode($posts_all);

要获得示例输出中的“状态”,您需要在代码中添加相同的状态。

api实际上返回编码的json,我只需确保其格式正确即可。还有什么我可以删除的
ok
posts
?真棒:)感谢您阅读文档找到问题的解决方案。不确定为什么有人否决了这个问题和所有答案,但我将回答标记为答案:)api实际上返回了编码的json,没有必要为thisRain,请通读代码,希望你能理解我想告诉你的,哇,似乎否决票的家伙在这里无理由否决一切!