Home > Backend Development > PHP Tutorial > mysql - laravel php 数据存储 Array toJson

mysql - laravel php 数据存储 Array toJson

WBOY
Release: 2016-06-06 20:31:29
Original
1818 people have browsed it

<code>$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('保存失败!');
  }
</code>
Copy after login
Copy after login

$goods 的到的数据 是一组数组

保存到数据库是就成了 Array 了

mysql - laravel php 数据存储 Array toJson

然后 用 json 转一下

<code>$goods = $goods->toJson();

</code>
Copy after login
Copy after login

toJson() 报错了

Call to a member function toJson() on array

有大神可以指导一下吗

回复内容:

<code>$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('保存失败!');
  }
</code>
Copy after login
Copy after login

$goods 的到的数据 是一组数组

保存到数据库是就成了 Array 了

mysql - laravel php 数据存储 Array toJson

然后 用 json 转一下

<code>$goods = $goods->toJson();

</code>
Copy after login
Copy after login

toJson() 报错了

Call to a member function toJson() on array

有大神可以指导一下吗

从你的foreach来看,最后的$goods是一个普通的数组,这个数组跟toJSON没有什么必然联系,在我的记忆中,toJSON应该不是php内置的吧。

想到的解决方案:

<code>$order -> json = json_encode($goods);

</code>
Copy after login

对于上面的代码,还有以下的建议:

<code>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;
}

</code>
Copy after login

上面这一段,我觉得你好好看看Eloquent的Relationship部分,这个应该会很好地解决了。

第二,else关键字其实很多时候是可以不用的:

<code>if( $order->save() ) {
       return response()->json(array( 'status' => 1, 'msg' => "下单成功"));
  }

 return Redirect::back()->withInput()->withErrors('保存失败!');

</code>
Copy after login

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

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template