您好,欢迎访问一九零五行业门户网

mysql - laravel php 数据存储 Array toJson

$goods = ;foreach($carts as $key => $c){ $good = goods::where([product_id => $c->product_id,merchant_id => $c->merchant_id])->first(); $good -> number = $c->number; $goods[] = $good;} $order = new order; $order -> json = $goods; if( $order->save()){ return response()->json(array( 'status' => 1, 'msg' => 下单成功)); }else{ return redirect::back()->withinput()->witherrors('保存失败!'); }

$goods 的到的数据 是一组数组
保存到数据库是就成了 array 了
然后 用 json 转一下
$goods = $goods->tojson();

tojson() 报错了
call to a member function tojson() on array
有大神可以指导一下吗
回复内容: $goods = ;foreach($carts as $key => $c){ $good = goods::where([product_id => $c->product_id,merchant_id => $c->merchant_id])->first(); $good -> number = $c->number; $goods[] = $good;} $order = new order; $order -> json = $goods; if( $order->save()){ return response()->json(array( 'status' => 1, 'msg' => 下单成功)); }else{ return redirect::back()->withinput()->witherrors('保存失败!'); }

$goods 的到的数据 是一组数组
保存到数据库是就成了 array 了
然后 用 json 转一下
$goods = $goods->tojson();

tojson() 报错了
call to a member function tojson() on array
有大神可以指导一下吗
从你的foreach来看,最后的$goods是一个普通的数组,这个数组跟tojson没有什么必然联系,在我的记忆中,tojson应该不是php内置的吧。
想到的解决方案:
$order -> json = json_encode($goods);
对于上面的代码,还有以下的建议:
foreach($carts as $key => $c){ $good = goods::where([product_id => $c->product_id,merchant_id => $c->merchant_id])->first(); $good -> number = $c->number; $goods[] = $good;}
上面这一段,我觉得你好好看看eloquent的relationship部分,这个应该会很好地解决了。
第二,else关键字其实很多时候是可以不用的:
if( $order->save() ) { return response()->json(array( 'status' => 1, 'msg' => 下单成功)); } return redirect::back()->withinput()->witherrors('保存失败!');
以上的代码应该也是行得通的
赞楼上,json_encode()是php最常用的内置函数之一,lz不要太过于依赖框架了
其它类似信息

推荐信息