laravel 刀片文件中的“数组到字符串转换错误”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37692408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:57:21  来源:igfitidea点击:

"Array to String Conversion Error" in laravel blade file

phplaravelblade

提问by horse

I have an $array_variablelike that in my laravel controller:

我的$array_variableLaravel 控制器中有一个类似的:

{"11161":{"total":1,"1":1,"2":0,"3":0,"4":0},"11160":{"total":1,"1":1,"2":0,"3":0,"4":0},"11159":{"total":5,"1":5,"2":0,"3":0,"4":0},"11158":{"total":1,"1":1,"2":0,"3":0,"4":0},"11157":{"total":2,"1":2,"2":0,"3":0,"4":0},"11156":{"total":2,"1":2,"2":0,"3":0,"4":0},"11155":{"total":1,"1":1,"2":0,"3":0,"4":0},"11154":{"total":2,"1":2,"2":0,"3":0,"4":0},"11153":{"total":1,"1":1,"2":0,"3":0,"4":0},"11152":{"total":2,"1":2,"2":0,"3":0,"4":0},"11151":{"total":2,"1":2,"2":0,"3":0,"4":0},"11137":{"total":2,"1":2,"2":0,"3":0,"4":0},"11150":{"total":2,"1":2,"2":0,"3":0,"4":0},"11136":{"total":2,"1":2,"2":0,"3":0,"4":0},"11135":{"total":1,"1":1,"2":0,"3":0,"4":0},"11132":{"total":2,"1":2,"2":0,"3":0,"4":0},"11134":{"total":2,"1":2,"2":0,"3":0,"4":0},"11133":{"total":2,"1":2,"2":0,"3":0,"4":0},"11121":{"total":2,"1":2,"2":0,"3":0,"4":0},"11120":{"total":1,"1":1,"2":0,"3":0,"4":0},"11119":{"total":1,"1":0,"2":1,"3":0,"4":0}}

When I access it in blade file via {{ $array_variable[$id] }}or {{ $array_variable }}, it gives this error:

当我通过{{ $array_variable[$id] }}或在刀片文件中访问它时{{ $array_variable }},它给出了这个错误:

ErrorException
Array to string conversion

How can I access array elements without error?

如何访问数组元素而不会出错?

回答by Filip Koblański

When you get $array_variable[$id]it gives you a subquery of:

当你得到$array_variable[$id]它时,它会给你一个子查询:

"total" => [(...)]

which isn't string. So that why you getting this error. The {{ (...) }}statement is for echoing data and when you try to echo array you get this error. You can give a try with something like this:

这不是字符串。所以这就是为什么你会收到这个错误。该{{ (...) }}语句用于回显数据,当您尝试回显数组时,会出现此错误。您可以尝试使用以下方法:

{{ 'total: ' . implode(', ', $array_variable[$id]['total']) }}

回答by Rahul M

It doesn't look like an array, but a json object.. in either case you cannot echo that. What you can do is: json_decode() it and then a for/each loop over it to echo the elements.

它看起来不像一个数组,而是一个 json 对象......在任何一种情况下你都不能回应它。你可以做的是: json_decode() 它然后一个 for/each 循环在它上面回显元素。

回答by emrhzc

use var_dump for printing arrays

使用 var_dump 打印数组

var_dump($array_variable[$id]);