0

I am trying to get the following output format from a CI query and subsequent JSON_encode:

{"clients":{"id":"3","name":"Client Number1"},{"id":"2","name":"Client Number2"},{"id":"1","name":"Test Client"},{"id":"4","name":"Test Client2"}}

Combining the small functions in the controller and the model, I am using:

$query = $this->db->query('SELECT id, name FROM clients ORDER BY name ASC');
        foreach ($query->result() as $row)
        {
            $arr['clients'][] = $row;
        }

        $json = json_encode($arr, JSON_FORCE_OBJECT);
        echo $json;

This code outputs (below) which includes the array index values ("1", "2"... etc.) How can I remove these index values from the result? Thanks for any help you may be able to give. This one is not a deal-breaking crisis. I could parse them out on the other side of the transaction... but thought the omniscient SO might know how to do this more elegantly!!

{"clients":{"0":{"id":"3","name":"Client Number1"},"1":{"id":"2","name":"Client Number2"},"2":{"id":"1","name":"Test Client"},"3":{"id":"4","name":"Test Client2"}}}
0

2 Answers 2

2

Edit: I was wrong.

Apparently all objects in PHP's json_encode print as associative arrays, and thus it always prints the keys. At least, that's the vibe I got from the page on json_encode in the PHP manual.

Removing JSON_FORCE_OBJECT (and using $query->result_array()) gets rid of the keys, but isn't exactly what you're looking for:

{"clients":[{"id":"3","name":"Client Number1"},{"id":"2","name":"Client Number2"},{"id":"1","name":"Test Client"},{"id":"4","name":"Test Client2"}]}
Sign up to request clarification or add additional context in comments.

1 Comment

Ha! Thanks! You must have been typing at the same time as me. :) I'll happily give you the up arrow and check mark!
1

Thanks Trevor... I appreciate the help. You actually pointed me in the right direction. I had forgotten that the 'JSON_FORCE_OBJECT' parameter might be messin' things up. In fact it was... see below:

$query = $this->db->query('SELECT id, name FROM clients ORDER BY name ASC');
        foreach ($query->result() as $row)
        {
            $arr['clients'][] = $row;
        }

        $json = json_encode($arr); // Note JSON_FORCE_OBJECT removed
        echo $json;

This code outputs:

{"clients":[{"id":"3","name":"Client Number1"},{"id":"2","name":"Client Number2"},{"id":"1","name":"Test Client"},{"id":"4","name":"Test Client2"}]}

I think that simply allowed a JSONArray (hence the square brackets) to live inside the JSONObject... I can live with that.

Thanks again Trevor!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.