【问题标题】:Json data return together in laravelJson数据在laravel中一起返回
【发布时间】:2019-06-30 02:32:37
【问题描述】:

我有包含这些数据的 json 列:

{
  "address":"testing address, phone number, country, state, name of the person etc.",
  "post_method":"tiki",
  "post_price":"15000",
  "weight":"2"
}

现在当我尝试在我的视图中返回这些数据时:

@foreach($order->shipment_data as $shipment) //shipment_data is the name of json column which holds this data
 {{$shipment}}
@endforeach

它将addresspost_methodpost_priceweight 下的所有数据一起返回,就像一个段落一样。

我无法分别获取每个部分,例如:

{{$shipment['post_price']}}

它返回:

非法字符串偏移'post_price'(查看:

有什么想法吗?

更新

{{dd($order->shipment_data)}}的结果

"{"address":"fake address here...","post_method":"tiki","post_price":"15000","weight":"2"} ◀"

【问题讨论】:

  • 在 post_price 之前先添加索引 0
  • @aldrin27 Illegal string offset
  • 你需要json_decode()数据吗?
  • @OluwatobiSamuelOmisakin 建议先解码你的 json。
  • @OluwatobiSamuelOmisakin 我不这么认为,因为在我使用json_encode 存储我的数据之前,它在每个部分之前添加了 \ 然后我删除了该编码代码,所以现在它实际上只是保存了一个数组@ 987654333@ 我不认为我需要解码,只要我不编码它们

标签: php json laravel laravel-blade


【解决方案1】:

你需要将json转换成数组。您可以使用 json_decode 函数来做到这一点。此外,如果您使用新版本的 Laravel,您可以通过添加

从 json 转换为模型中的数组
protected $casts = [
    'shipment_data' => 'array',
];

这应该可以工作。

【讨论】:

  • 你只需要 {{$order->shipment_data->post_price}} 没有循环
【解决方案2】:

由于您已经将其转换为数组,因此在您的情况下,$order->shipment_data 只是一个数组。您可以按如下方式访问各个列:

$order->shipment_data['post_price']

不需要foreach()

【讨论】:

  • 上面写着Trying to get property 'post_price' of non-object
  • 您确实需要使用json_decode()。查看更新的答案。
  • 当我按照你的方式行事时 @foreach(json_decode($order->shipment_data) as $shipment) 它说 json_decode() expects parameter 1 to be string, array given
  • 您可以dd($order->shipment_data) 并将其添加到您的问题中吗?
  • 更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多