开发者

PHP and Codeigniter. How to return an array object and not plain array?

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

Thankful for all input!


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜