Convert laravel object to array

前端 未结 14 729
名媛妹妹
名媛妹妹 2020-12-13 19:33

Laravel output:

Array
(
    [0] = stdClass Object
    (
        [ID] = 5

    )

    [1] = stdClass Object
    (
        [ID] = 4

    )

)

相关标签:
14条回答
  • 2020-12-13 20:16
    $res = ActivityServer::query()->select('channel_id')->where(['id' => $id])->first()->attributesToArray();
    

    I use get(), it returns an object, I use the attributesToArray() to change the object attribute to an array.

    0 讨论(0)
  • 2020-12-13 20:16

    Object to array

    $array = (array) $players_Obj;  
    
    $object = new StdClass;
    $object->foo = 1;
    $object->bar = 2;
    
    var_dump( (array) $object );
    

    Output:

    array(2) {
        'foo' => int(1)
        'bar' => int(2)
    }
    
    0 讨论(0)
  • 2020-12-13 20:17

    I suggest you simply do this within your method

    public function MyAwesomeMethod($returnQueryAs = null)
    {
        $tablename = 'YourAwesomeTable';
    
        if($returnQueryAs == 'array')
        {
            DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
        }
    
        return DB::table($tablename)->get();
    }
    

    With this all you need is to pass the string 'array' as your argument and Voila! An Associative array is returned.

    0 讨论(0)
  • 2020-12-13 20:18

    UPDATE since version 5.4 of Laravel it is no longer possible.

    You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:

    DB::setFetchMode(PDO::FETCH_ASSOC);
    
    // then
    DB::table(..)->get(); // array of arrays instead of objects
    
    // of course to revert the fetch mode you need to set it again
    DB::setFetchMode(PDO::FETCH_CLASS);
    

    For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section

    Event::listen(StatementPrepared::class, function ($event) {
        $event->statement->setFetchMode(...);
    });
    
    0 讨论(0)
  • 2020-12-13 20:20

    Just in case somebody still lands here looking for an answer. It can be done using plain PHP. An easier way is to reverse-json the object.

    function objectToArray(&$object)
    {
        return @json_decode(json_encode($object), true);
    }
    
    0 讨论(0)
  • 2020-12-13 20:21

    Its very simple. You can use like this :-

    Suppose You have one users table and you want to fetch the id only
    $users = DB::table('users')->select('id')->get();
    $users = json_decode(json_encode($users)); //it will return you stdclass object
    $users = json_decode(json_encode($users),true); //it will return you data in array
    echo '<pre>'; print_r($users);
    

    Hope it helps

    0 讨论(0)
提交回复
热议问题