Search code examples
phpcodeigniterobjectresultset

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"
}

Solution

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