j4mie/idiorm

as_array for multiple results

j4mie opened this issue · 9 comments

From Osman Üngür (by email):

Is as_array() can be usable with find_many() for array output ? (I tested, as_array() with
find_many() gives me an error)
(Its simply possible with iterating result object to Redis Lists but i want to set json encoded
array output to Redis key) (I dont want to iterate it again and again)

Idea: Make as_array() work on unexecuted queries. So, you could call
ORM::for_table('table')->as_array();

I solve the problem this (into idiorm.php):

    public static function to_array( $arr_orm ) {
        $salida = array();
        
        if( is_array( $arr_orm ) ) {
            $size = sizeof( $arr_orm );
        
            for( $i = 0; $i < $size; ++$i ) {
                $obj = $arr_orm[$i];

                if ( $obj instanceof ORM ) {
                    $salida[$i] = $arr_orm[$i]->as_array();
                }
            } 
        }
        
        return $salida;
    }

And you can use this way:

$tnomina = ORM::for_table('nomina.tnomina')->find_many(); ORM::to_array( $tnomina )

Hello, here's my correction for the above solution :

public static function to_array($result) {
    $array = array();
    foreach ($result as $r) {
        $array[] = (array) $r->_data;
    }
    return $array;
}
Surt commented

You don't need that code, use this one instead... less resources consuming since _run it's returning the array you are looking for:

    public function find_array() {
        return $this->_run(); 
    }

$tnomina = ORM::for_table('nomina.tnomina')->find_array();

@Surt Where should this code go? If I try accessing the properties of my orm objects in my application, I just get null values, presumably because the properties are protected?

Surt commented

It goes directly before, or after find_many or find_one, as another method.
since
[code]
return $this->_run();
[/code]
returns an array, you will end with a raw array:

$tnomina = ORM::for_table('nomina.tnomina')->find_array();
var_dump($tnomina); // will return

array(
0 => array(....a row),
1 => array(...another row),
.
.
);

@Surt - thanks. Works great. Perhaps there should be a PR for this?

@Surt, man it's great) thanks a lot.

I like @Surt approach to this problem so adding a find_array method for 1.2.0. Closed in commit 3c082ca