We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Non-recursive toArray?

Is there any option to get a result set as an array without the recuirsive nature of toArray.

1) Being able to get a complete result set as an array is a common requirement.

2) An array of objects is preferable to an array of arrays because it allows the much neater Volt syntax of object.property as opposed to array['element']

3) Unfortunately,->setHydrateMode(Resultset::HYDRATE_OBJECTS)->toArray() returns an array of arrays rather than an array of objects, which is counter intuitive and non-useful.

Just an idea, but how about a 'recursive = false' parameter for toArray (or default to true as a comromise for BC), and is there already a builtin way to return just as array of result objects?

== Edit ===

As result sets are iterable, simply passing an object hydrated result set into volt of course works fine, so toArray isn't required for that scenario, but for cases where an array is desired, a non-recursive option would be nice.



17.5k
edited Aug '15

Not sure if it's recursive or not, but I almost never use toArray() in favor of returning the queried object as a json block like this:

    $blah = new Blah();
    $stuff = $blah->find();
    echo json_encode($stuff);

Might be a better solution? Works well for me, regardless.



3.8k

Thanls for the reply. We do this too in fact, having a DI'd AngularJS Component that handles returning results to an Angular service. The end of an action will typically look like:

$this->angularjs->respond(true, php_object);

where the component handles turning the result into json and various other things, particularly in the case where the action has failed. In the case I first had in mind when first posting toArray wasn't actually needed after all, hence my edit, but I'm sure that it would be useful sometimes, and in that case it's possibly not what's really wanted. There are always some unfortunate or incorrect design choices in frameworks so this is par for the course. Phalcon also has an illogical order to parameters in relationship statements, is missing a trick by only using magic get/set for related models, should accept objects as well as strings in logger routines, and so on, but Phalcon is also flexible and most shortcomings or however one views them can be fixed, so it's not a disaster.