Converting object to array in laravel [duplicate] Converting object to array in laravel [duplicate] laravel laravel

Converting object to array in laravel [duplicate]


Using array_map and casting to an array should be sufficient:

$data = array_map(function($object){    return (array) $object;}, $data);

I also wouldn't run queries inside a loop. You should try getting that data in one query from the db. Something like this could work:

$data = DB::table('order_details')    ->join('orders', 'order_details.oid', '=', 'orders.oid')    ->select('order_details.oid', 'orders.ostatus')    ->whereIn('order_details.oid', $oid)->get();

Edit

As it has been mentioned in another answer shortly let me explain how you can accomplish the same by setting PDO to FETCH_ASSOC:

DB::setFetchMode(PDO::FETCH_ASSOC);$data = DB::table('order_details') .... ->get();

However this changes the fetch mode globally for the rest of the request (at least if you don't open a new connection). To be save you should change it back afterwards:

DB::setFetchMode(PDO::FETCH_ASSOC);$data = DB::table('order_details') .... ->get();DB::setFetchMode(PDO::FETCH_CLASS);

Or even back it up first if you can't be sure what default is used:

$fetchModeBefore = DB::getFetchMode();DB::setFetchMode(PDO::FETCH_ASSOC);$data = DB::table('order_details') .... ->get();DB::setFetchMode($fetchModeBefore);


On the PDO/DB object you can set the return style to assoc.