Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Get simple array from model instead of object

Hi, I'm trying to get a simple array from my database like:

    array(43, 54, 5)

What I'm trying is:

    $robot_ages = RobotAges::find(["hydration" => \Phalcon\Mvc\Model\Resultset::HYDRATE_OBJECTS])->toArray();

With that, I get something like this:

    array(
        array(
            43
        ),
        array(
            54
        ),
        array(
            5
        )
    )

Not sure if it's possible, array_map ?

How do you even get that result without column names in the array?

When I run:

$items = News::find([
    'hydration' => \Phalcon\Mvc\Model\Resultset::HYDRATE_OBJECTS
])->toArray();

// Output
Array
(
    [0] => Array
        (
            [id] => 1
            [is_active] => 1
            [category_id] => 4
            [created_at] => 2016-02-02
        )

    [1] => Array
        (
            [id] => 2
            [is_active] => 1
            [category_id] => 10
            [created_at] => 2016-02-02
        )
)

When I specify columns:

$items = News::find([
    'columns' => 'id', 
    'hydration' => \Phalcon\Mvc\Model\Resultset::HYDRATE_OBJECTS
])->toArray();

// Output
Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [id] => 2
        )
)

Your best option would be just to foreach the result and build any custom array format you need. You can even take it one step further by defining a method in a BaseModel which does this. Of course if you need it frequently in your application.



4.7k

How do you even get that result without column names in the array?

Good point :) My approach is simplified. I tried a foreach inside my controller but I got a exception. I will post the message later.



114.4k
Accepted
answer
edited Jul '16

Try do it like this maybe:

$robot_ages = array_map(function($v) {
    return $v['id'];
}, RobotAges::find(["hydration" => \Phalcon\Mvc\Model\Resultset::HYDRATE_OBJECTS])->toArray());

@Wojciech, perhaps edit your answer with return $v['id']; and also specificying which columns to be fetched :)



4.7k

Works like charm, thanks alot an have a nice day!

Also remember that for big resultset you shouldn't really use it beacause it's slower than foreach.

A sidenote:

Why not just hydrate the resultset as arrays, rather than objects you then convert to arrays?

Agree, but I guess it was left like that due to the many test attempts by @ndabap

A sidenote:

Why not just hydrate the resultset as arrays, rather than objects you then convert to arrays?