使用CodeiGniter格式化json



我使用的是codeigniter php,我需要制作一个返回包含书籍模型的数组的api rest,为此,我在控制器中创建了一个名为api2.php的文件,我在这里输入了rest调用的返回,所以api2.php调用。问题是,调用返回的json格式不正确,应该是另一种格式。

Json Now(不正确(:https://gist.github.com/riccardopirani/8b41fe97896380e64b5df1f92f99b954

更正json:

{  
[
id: "2", 
desc: "sss",
..
],
[ 
id: "3", 
desc: "sss",
..
], 
}

控制器/Api2.php:

<?php
class Api2 extends CI_Controller {

function __construct() {
parent::__construct();
$this->load->model('Book_model');
}

function index() {
header('Content-Type: application/json');      
$values = $this->Book_model->get_all_books();
$book_list = [];

foreach ($values as $row)
{

$book_list[$row['id']] = $row['id'];
$book_list[$row['cat']] = $row['cat'];
$book_list[$row['descrizione']] = $row['descrizione'];
$book_list[$row['titolo']] = $row['titolo'];
$book_list[$row['prezzo']] = $row['prezzo'];
$book_list[$row['autore']] = $row['autore'];
$book_list[$row['order']] = $row['order'];
}
echo json_encode($book_list);
}
}

Models/Book_model.php:

<?php
class Book_model extends CI_Model
{
function __construct()
{
parent::__construct();
}

/*
* Get book by id
*/
function get_book($id)
{
return $this->db->get_where('books',array('id'=>$id))->row_array();
}

/*
* Get all books
*/
public function get_all_books()
{
$this->db->order_by('id', 'desc');
return $this->db->get('books')->result_array();
}

/*
* function to add new book
*/
function add_book($params)
{
$this->db->insert('books',$params);
return $this->db->insert_id();
}

/*
* function to update book
*/
function update_book($id,$params)
{
$this->db->where('id',$id);
return $this->db->update('books',$params);
}

/*
* function to delete book
*/
function delete_book($id)
{
return $this->db->delete('books',array('id'=>$id));
}
}

您的错误表明,它期望对象的结果名为renderers,但它未定义,因此如果您没有调试js代码的经验,则必须在此处声明它,并相应地更改预期结果:

$values = $this->Book_model->get_all_books();
$this->output->set_header("Access-Control-Allow-Origin: *");
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode(["renderers" => $values]));

将数据解析为数组,并将其处理为json

function index() {
header('Content-Type: application/json');
//print link element
/*$array = array(
"foo" => "bar",
"bar" => "foo",
);*/
$values = $this->Book_model->get_all_books();
book_list = [];

foreach ($values as $row)
{
$book_list[$row['id']] = $row['id'];
$book_list[$row['desc']] = $row['desc'];
}
return $book_list;
echo json_encode($book_list);
}

使用Output类回显json内容

function index() {
$values = $this->Book_model->get_all_books();
$this->output
->set_content_type('application/json')
->set_output(json_encode($values));
}

相关内容

  • 没有找到相关文章

最新更新