首页 > laravel php 数据存储 Array toJson

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

有大神可以指导一下吗


赞楼上,json_encode()是php最常用的内置函数之一,lz不要太过于依赖框架了


从你的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('保存失败!');

以上的代码应该也是行得通的

【热门文章】
【热门文章】