Jonathan Clark
Jonathan Clark

Reputation: 20538

How to return a single row result from a query as an object?

In Codeigniter I am creating an array and returning it to the user. I am creating the array like this (result is the return form a DB query):

array("email" => $result)

Right now it outputs:

"email": [
    {
        "id": "629",
        "desc": "0000",
        "value_1": "0000",
        "value_2": null,
        "value_3": null,
        "value_4": null,
        "privacy": "0"
    }
]

So $result is an array that contains a single object. How can I make $result contain just the object instead? Like this:

"email": {
    "id": "628",
    "desc": "THIS IS IT",
    "value_1": "THIS IS IT2",
    "value_2": null,
    "value_3": null,
    "value_4": null,
    "privacy": "0"
}

Upvotes: 1

Views: 4519

Answers (3)

Sam Starling
Sam Starling

Reputation: 5378

Just use:

array("email" => $result->row());

See the CI documentation on queries and row():

This function returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an object.

Upvotes: 3

Shadow Wizard
Shadow Wizard

Reputation: 66389

The first defines email as an object.

The second defines email as plain array with one item, and that item is an object by itself.

For example, to access id property using the first form of email you should have:

var id = obj.email.id;

In the second form:

var id = obj.email[0].id;

Edit: answer to your new question "How can I get the second one to look like the first one" - you can't. The second form is defining whole different thing, you just have to change the way you access that email and if always have one item, use email[0] like in the above sample code.

Upvotes: 1

ZenMaster
ZenMaster

Reputation: 12742

First one is a JSON Object that has a property/member email that is, in turn, a JSON Object that contains properties id, desc etc.

The second one, on the other hand, is a JSON Object that has a property email that is a JSON Array that contains 1 element that has properties id, desc etc.

Basically, if I were to translate the access to the value of value_1 field:

1 object:

obj.email.value_1

2 object:

obj.email[0].value_1

Upvotes: 1

Related Questions