这里我正在做一个json_encode
public function get_posts_for_category($user_id,$category_id,$page)
{
$cat_id = $this->ApiModel->get_category_id($category_id);
$total_row = $this->ApiModel->get_category_posts_count($cat_id->category);
$per_page = 2;
$total_pages = $total_row / $per_page;
$posts = $this->ApiModel->get_category_posts($cat_id->category,$per_page,$page);
$data = array();
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id,$post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp);
$data[] = array('page' => $page, 'posts' => $array, 'is_favorite' => $status);
}
echo strip_tags(json_encode($data));
}
我从上面的代码得到的输出是
但我想要这样的事情
答案 0 :(得分:0)
<?php
public function get_posts_for_category($user_id,$category_id,$page)
{
$cat_id = $this->ApiModel->get_category_id($category_id);
$total_row = $this->ApiModel->get_category_posts_count($cat_id->category);
$per_page = 2;
$total_pages = $total_row / $per_page;
$posts = $this->ApiModel->get_category_posts($cat_id->category,$per_page,$page);
$data = array();
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id,$post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp, 'is_favorite' => $status);
$data[] = array('page' => $page, 'posts' => $array, 'total_posts' => count($posts), 'total_pages' => $total_pages);
}
echo strip_tags(json_encode($data));
}
?>
答案 1 :(得分:0)
$return = array(
'page' => $page,
'total_posts' => $total_row,
'total_page' => $total_pages,
);
$data = [];
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id, $post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp, 'is_favorite' => $status);
$data[] = $array;
}
$return['posts'] = $data;
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($return));
只需将此代码替换为foreach
&amp; echo
声明。
你永远不应该将strip_tags
与json_encode
结合使用,因为你已经在编码数据,它的接收者选择做任何他想做的事情,在这个过程中你可能会破坏编码。 / p>
此外,您应该使用CI
输出库发送响应,您不得回显控制器中的任何内容。有关详细信息,请参阅此处https://ellislab.com/codeigniter/user-guide/libraries/output.html
答案 2 :(得分:0)
如果您希望输出数值,(而不是字符串),您可能希望尝试:
json_encode($return, JSON_NUMERIC_CHECK);
要很好地格式化输出的JSON(缩进等),请使用:
json_encode($return, JSON_PRETTY_PRINT);
您可以按照json_encode's options使用上述的各种组合。
对于布尔值(而不是&#34; true&#34;和&#34; false&#34;作为字符串返回),您需要首先将它们转换为布尔类型:
$status = (bool) true;