Posted by & filed under PHP, Programming.

Two simple ways to convert a ActiveRecord object into a array:

  1. Using cHTML::ListDatause CHtml::listData (see www.yiiframework.com/wiki/48/by-example-… )
    $users = User::model()->findAll();
    $usersArr = CHtml::listData( $users, 'id' , 'city');
    print_r( $usersArr );

    It will give you array id => city

    Array {
        2 => 'Paris',
        102 => 'Riga',
        // ...
    }
  2. Using array_map (used this method last time, array_map rocks):
    $words = Word::model()->findAll();
    $data=array_map(create_function('$m','return $m->getAttributes();'),$words);
    var_dump($data);

 

Leave a Reply

You must be logged in to post a comment.