dongzhuifeng1843 2011-05-06 21:36
浏览 78
已采纳

获取PHP ActiveRecord结果作为简单数组,而不是对象数组

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
    )
  • 写回答

8条回答 默认 最新

  • duancutan4770 2011-08-17 15:45
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法