迭代刀片json数据

时间:2016-10-12 17:57:51

标签: php laravel laravel-blade

我试图在foreach循环中迭代一个json对象,但没有成功,它一直给我关于html实体的错误。

我试图在我的foreach中输出的数据如上:

数据: 存储上述数据的变量是'$ product->标签['data']'

{"tags":[{"type":"circle","points":[[1.0449999570846558,0.5450000166893005],[0.9850000143051147,0.4399999976158142]],"popup":{"title":"my title","description":"my description"}},{"type":"rectangle","points":[[0.03500000014901161,0.125],[0.3400000035762787,0.6000000238418579]],"popup":{"title":"roupa","description":"guardar roupa"}}]}

我的代码:

@foreach($product->tags['data']->tags as $tag){
{{$tag->type}}
}

我的错误: 无效argument supplied for foreach()

2 个答案:

答案 0 :(得分:0)

    $product->tags['data'] = '{"tags":[{"type":"circle","points":[[1.0449999570846558,0.5450000166893005],[0.9850000143051147,0.4399999976158142]],"popup":{"title":"my title","description":"my description"}},{"type":"rectangle","points":[[0.03500000014901161,0.125],[0.3400000035762787,0.6000000238418579]],"popup":{"title":"roupa","description":"guardar roupa"}}]}';
    $product->tags['data'] = json_decode($product->tags['data'], true);

    foreach($product->tags['data']['tags'] as $tag)
        echo $tag['type'].'<br>';

答案 1 :(得分:0)

假设你的json是:

$json='{"tags":[{"type":"circle","points":[[1.0449999570846558,0.5450000166893005],
[0.9850000143051147,0.4399999976158142]],
"popup":{"title":"my title","description":"my description"}},
{"type":"rectangle","points":[[0.03500000014901161,0.125],
[0.3400000035762787,0.6000000238418579]],"popup":{"title":"roupa","description":"guardar roupa"}}]}';

我假设您在将json传递给视图时没有对其进行解码,因此您必须在控制器中执行此操作:

return view('sample')->with('data',json_decode($json));

json_decode 是将您的json数据解码为可在刀片中迭代的函数。

现在,在您的刀片模板中,您可以像这样遍历标记:

@foreach($data->tags as $tag)
  {{$tag->type}}
  <br/>
@endforeach