문제

I would like to have a simple a method, that can give back PHP Activerecord results as simple/associative arrays, not an array of ActiveRecord Objects.

In Ruby I believe this is done perhaps with .map() method. (I am not a Ruby guy...)

What I want is a simple method call, like toArray() in Zend_DB_Table, not a foreach, or something like that, but I can't seem to find it in their docs.

In PHP ActiveRecord getting a result is really easy:

$settings = SystemSettings::all();

But it gives back something like this:

[0] => SystemSettings Object
    (
        [errors] => 
        [attributes:ActiveRecord\Model:private] => Array
            (
                [param] => author
                [value] => Hawle
            )

        [__dirty:ActiveRecord\Model:private] => Array
            (
            )

        [__readonly:ActiveRecord\Model:private] => 
        [__relationships:ActiveRecord\Model:private] => Array
            (
            )

        [__new_record:ActiveRecord\Model:private] => 
    )

[1] => SystemSettings Object
    (
        [errors] => 
        [attributes:ActiveRecord\Model:private] => Array
            (
                [param] => base_url
                [value] => example.com
            )

        [__dirty:ActiveRecord\Model:private] => Array
            (
            )

        [__readonly:ActiveRecord\Model:private] => 
        [__relationships:ActiveRecord\Model:private] => Array
            (
            )

        [__new_record:ActiveRecord\Model:private] => 
    )

While this is really great in many cases, here, I would just like to have a simple array, like this:

Array
    (
        [author] => Hawle
        [base_url] => example.com
    )
도움이 되었습니까?

해결책

I had a similar issue hopefully this can help someone else who stumbles on it. Obviously, this is specific to phpactiverecord.org.

In /lib/Model.php I added the following function:

public function to_array(array $options=array())
{
    return $this->serialize('array', $options);
}

In /lib/Serialization.php I added the following class

class arraySerializer extends Serialization
{
    public static $include_root = false;

    public function to_s()
    {
        return self::$include_root ? array(strtolower(get_class($this->model)) => $this->to_a()) : $this->to_a();
    }


}

I can then call ->to_array() and get an array back.

Hope this helps!

다른 팁

I was searching for the answer to this question in order to produce an array of results that could be easily json-encoded and sent as the response to an ajax call. I wanted only the attributes of each object in the array of results.

Unfortunately, you can't just call to_json() on each result and then json-encode the entire thing; you end up with double-encoding. Fortunately, though, the function and class posted by @willwashburn to solve this problem have now been included in php-activerecord, though they don't seem to have made it into the online documentation.

To return an array of results, do the following:

$data = MyModel::find('all');
foreach ($data as &$result) {
    $result = $result->to_array();
}

Your entire result set will now be an array of arrays, containing only the attributes of each object. You can then do something like

echo(json_encode($data));

if you want to send it as the response to an ajax call.

class MyPHPActiveRecord extends PHPActiveRecord {

    public function toJSON() {
        return json_encode(get_object_vars($this));
    }
}

This is my solution:

$posts = Post::find('all');

$arrayResult = array_map(function($res){
  return $res->attributes();
}, $posts);
printf('<pre>%s</pre>', print_r($arrayResult, true));

You could do it like this:

funciton ar2array($settings){
   $arr = array();
   foreach($settings as $fieldObj){
      $fieldName = $fieldObj->attributes["param"];
      $fieldValue = $fieldObj->attributes["value"];
      $arr[$fieldName] = $fieldValue;
   }
   return $arr;
}
$resultAsYouWant = ar2array($settings);

Hope this helps. Cheers

PS: If ->attributes is private use its accesor method (there must be one) as ->getAttributes() or equivalent.

I found this looking for solution of the same problem that I encountered using Yii framework - there is simplier way to do this in Yii.

$posts = Posts::model()->findAll();

foreach($posts as $result)
{
    print_r($result->attributes);
}

It prints simple array as requested:

Array
(
    [id] => 1
    [title] => Title
    [text] => Text
)

Hope it helps somebody.

My solution:

  1. Added the following method to the utils class found in lib\Utils.php

    public static function results_to_json($data)
    {
    $arr = array();
    if(count($data)>0){
        foreach($data as $row){
            array_push($arr, $row->to_array());
        }
    }
    return json_encode($arr);
    }
    
  2. Call by:

    echo \ActiveRecord\Utils::results_to_json($dataobject);
    

Obviously this is no longer relevant to the OP; however, considering that it still took me over an hour to find a solution for this (no thanks to php-activerecords docs), this may help someone else.

 $r = Model::find('$id')->attributes();
 $a = [];
 foreach ($r as $k => $v)
 {
     $a[$k] = $v;
 }

Perhaps not the most elegant, but works perfectly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top