0

I am outputting the data in JSON format from MySQL database in controller like this,

function byId(){
        $this -> load -> model('usermodel');
        $data['user'] = $this -> usermodel -> getById($this->uri->slash_segment(3));
        $this -> output -> set_content_type('application/json');
        $this -> output -> set_output(json_encode($data));
    }

Model:

function getById($id){
        $this->db->select('*');
        $this->db->from('members');
        $this->db->where('id', $id);

        $q = $this -> db -> get();

        if ($q -> num_rows() > 0) {
            foreach ($q->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }

    }

It outputs the data like this,

{"user":[{"id":"3","firstname":"Frances","lastname":"Johnson","address":"489 Summit Lane","state":"Minnesota","country":"US","email":"fjohnson@teklist.net","phone":null,"experience":"2","designation":"Script"}]}

But I need it like this,

{user : {....} }

Basically I want to get rid of square brackets.

What can I change in my code to get the intended output?

John Altar
  • 141
  • 2
  • 13
  • It's hard to tell without knowing what the `Usermodell::getById` method does. From the json output it seems like you get an array back with numbered keys (like multiple rows from a database query) not a single row that you would expect. What does `var_dump($data['user'])` looks like? – complex857 Sep 15 '13 at 20:12
  • Let me edit it to give you more information. – John Altar Sep 15 '13 at 20:14

2 Answers2

1

The reason you see an extra [] around the individual "user" objects is because of the $data[] array in the getById() method. You are returning an array with other arrays inside them and by default json_encode will convert numerically indexed arrays (starting from 0) as javascript arrays.

Now it depends what's your intent here. If you wanted to return a list of an users even if it has one element but force the list containing the individual user objects as an object in the json output you can go with JSON_FORCE_OBJECT option like:

json_encode($data, JSON_FORCE_OBJECT);

But judging from your code, you just want to return the actual user object not a list of it, so you can either modify the getById() method to return the that with ->row() on the db result, or you can grab the first object returned from the method with:

...->getById(...)[0]; // for php 5.4+

or

 reset(...->getById()); // for older versions
complex857
  • 20,425
  • 6
  • 51
  • 54
0

Try replacing the line

$data['user'] = $this -> usermodel -> getById($this->uri->slash_segment(3));

with this

$data['user'] = $this -> usermodel -> getById($this->uri->slash_segment(3))[0];

[{ ... }] is an array containing a single object. [0] should grab the first element in that array rather than the array itself.

George Brighton
  • 5,131
  • 9
  • 27
  • 36