Pin*_*wer 2 php arrays laravel
我有这个代码:
$response['data'] = DB::table('customers')
->select(DB::raw('name,email,address1,address2,postalcode,state_region,country_code,phone,created_at'))
->where('user_id',"=",Auth::user()->id)
->where('name','like',"%$search_value%")
->orWhere('address1',"%$search_value%")
->orWhere('email','like',"%$search_value%")
->orWhere('address2','like',"%$search_value%")
->orWhere('city','like',"%$search_value%")
->orWhere('postalcode','like',"%$search_value%")
->orWhere('state_region','like',"%$search_value%")
->orWhere('country_code','like',"%$search_value%")
->orWhere('phone','like',"%$search_value%")
->orderBy('name', $order)
->limit($length)
->offset($start)
->get()->toArray();
Run Code Online (Sandbox Code Playgroud)
这个的结果是这样的:
'data' =>
array (size=10)
0 =>
object(stdClass)[194]
public 'name' => string '|Barbara User' (length=13)
public 'email' => string 'email@email.com' (length=16)
public 'address1' => string 'address aaddress' (length=17)
public 'address2' => null
public 'postalcode' => string '00000000' (length=10)
public 'state_region' => string 'GA' (length=2)
public 'country_code' => string 'US' (length=2)
public 'phone' => string '12312312312' (length=10)
public 'created_at' => string '2017-01-02 15:20:20' (length=19)
1 =>
object(stdClass)[201]
public 'name' => string '|Barbara User' (length=13)
public 'email' => string 'email@email.com' (length=16)
public 'address1' => string 'address aaddress' (length=17)
public 'address2' => null
public 'postalcode' => string '00000000' (length=10)
public 'state_region' => string 'GA' (length=2)
public 'country_code' => string 'US' (length=2)
public 'phone' => string '12312312312' (length=10)
public 'created_at' => string '2017-01-02 15:20:20' (length=19)
....
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,即使我已经做了一个,结果中仍然有一个对象toArray()
.
这里似乎有什么问题?
对你的帮助表示感谢!谢谢!
pat*_*cus 13
当您调用toArray()
a时Collection
,如果基础项实现了Illuminate\Contracts\Support\Arrayable
接口,则集合将尝试调用toArray()
每个项.但是,当您使用查询生成器,其结果将是一个Collection
的stdClass
对象,stdClass
对象是不实现该接口并没有一个简单的对象toArray()
方法.因此,当你调用toArray()
上Collection
的stdClass
对象,你只会得到一个普通数组stdClass
对象回来.
如果改用口若悬河,定义了一个Customer
模型,并使用该模型来进行查询,您的结果将是一个Collection
的Customer
模型,这些模型做实现Arrayable
接口.所以,当你调用toArray()
这个Collection
,它会调用toArray()
上的每一个项目Collection
,你的结果将是一个数组的数组.
如果由于某种原因,您不想使用Eloquent,则需要手动将项目从对象转换为数组.您可以使用map
或transform
上的方法轻松完成此操作Collection
.使用map
,如果你想返回一个新的Collection
,独自离开了原来的一个,或者使用transform
,如果你只是想修改原始Collection
.
$response['data'] = DB::table('customers')
// query conditions, etc
->get()
->map(function ($item, $key) {
return (array) $item;
})
->all();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5182 次 |
最近记录: |