在laravel转换对象数组 [英] Converting object to array in laravel
问题描述
我问这样它让我一个数组DB:
i queried a DB like this which got me an array:
foreach($oid as $orderid) {
$orderdetailData[] = DB::table('order_details')
->join('orders', 'order_details.oid', '=', 'orders.oid')
->select('order_details.oid', 'orders.ostatus')
->where('order_details.oid', $orderid)->get();
}
$data = array_flatten($orderdetailData);
return $data;
这是数组我得到
array (size=2)
0 =>
object(stdClass)[174]
public 'oid' => int 1
public 'ostatus' => string 'Placed' (length=6)
1 =>
object(stdClass)[158]
public 'oid' => int 2
public 'ostatus' => string 'Placed' (length=6)
我试图让这个数组的形式
I am trying to get this array in the form
array (size=2)
0 =>
array (size=2)
public 'oid' => int 1
public 'ostatus' => string 'Placed' (length=6)
1 =>
array (size=2)
public 'oid' => int 2
public 'ostatus' => string 'Placed' (length=6)
我试着这样做:
foreach($orderdetailData as $key => $value){
$data[] = array_flatten($orderdetailData[$key]);
}
但是,这样做让我的数组形式如下:
But doing this gets me an array in this form:
array (size=2)
0 =>
array (size=1)
0 =>
object(stdClass)[174]
public 'oid' => int 1
public 'ostatus' => string 'Placed' (length=6)
1 =>
array (size=1)
0 =>
object(stdClass)[158]
public 'oid' => int 2
public 'ostatus' => string 'Placed' (length=6)
这是不是我什么,我期待的。谁能告诉我这将是一个简单的方法来做到这一点?谢谢
Which is not i what i am looking for. Can someone tell me what would be an easy way to do this ? Thanks
推荐答案
使用 array_map
,并转换为数组应该是足够:
Using array_map
and casting to an array should be sufficient:
$data = array_map(function($object){
return (array) $object;
}, $data);
我也不会运行在一个循环内的查询。你应该尝试获得从DB一个查询的数据。像这样的东西可以工作:
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();
修改
因为它已经在另一个答案被提到不久让我解释如何通过PDO设置为 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);
这篇关于在laravel转换对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!