[英]CodeIgniter Convert Array to Json
the php code below uses codeigniter for a select on a db, so the array must then be converted to do so I use the code below but it does not convert the json (the json is reported in gist) therefore it is not cast to a json 阵列。
json的要点链接: https://gist.github.com/riccardopirani/2a48e8e62fa6825c512
Controller.php
class Api2 extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Book_model');
}
function index() {
header('Content-Type: application/json');
//print link element
$array = array(
"foo" => "bar",
"bar" => "foo",
);
$values["data"] = $this->Book_model->get_all_books();
/*foreach($_GET as $key => $value){
echo $key . " : " . $value . "\n";
} */
//Return data
// $data = json_encode($tempdata);
print_r(json_encode($values["data"]));
return (json_encode($values["data"]));
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));
}
}
我认为您应该在 Api2 Controller 上放置echo
而不是return
public function index()
{
header('Content-Type: Application/json');
$values['data'] = $this->Book_model->get_all_books();
echo json_encode($values['data']);
}
或者您可以使用 CodeIgniter 中的内置output
output
public function index()
{
$values['data'] = $this->Book_model->get_all_books();
$this->output
->set_content_type('application/json', 'utf8')
->set_output( json_encode($values['data']) );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.