John Davidson

php - CodeIgniter Convert Array to Json

0 comments
Message:


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 array.


Gist link of json: https://gist.github.com/riccardopirani/2a48e8e62fa65512fd487de0ca82bc79


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));
}
}


My Answer:
load->model('Api_model');_ }_ function get_data() {_ $data = $this->Api_model->get_data_from_db();_ $json_data = json_encode($data);_ echo $json_data;_ }_}_Model.php_class Api_model extends CI_Model {_ function get_data_from_db() {_ $query = $this->db->get('table_name');_ return $query->result_array();_ }_}In the code above, the `get_data` function in the `Api2` controller retrieves data from the database using the `get_data_from_db` function in the `Api_model` model. The retrieved data is then encoded to JSON using `json_encode` and echoed out.

If the JSON output is not as expected, you may want to check the data being returned from the database and ensure it is in the correct format for JSON encoding. You can also use `var_dump` or `print_r` to debug the data before encoding it to JSON.

Rate this post

3 of 5 based on 9610 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us