laravel htmlspecialchars 期望参数 1 是字符串,给定数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51004362/
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 17:50:21  来源:igfitidea点击:

htmlspecialchars expects parameter 1 to be string, array given

phphtmllaravellaravel-blade

提问by Enrique Bermúdez

I am getting the next error while printing a model content on my blade.php view:

在我的blade.php 视图上打印模型内容时出现下一个错误:

htmlspecialchars() expects parameter 1 to be string, array given

This model "content" is a column (json type) in a table and it looks just like this:

这个模型“内容”是表中的一列(json 类型),它看起来像这样:

[{"Item":2}]

And this is how i'm trying to use it on my view:

这就是我试图在我的观点中使用它的方式:

@foreach ($post->loot->content as $name => $amount)
     <div class="item">
          <i class="fab fa-cuttlefish"></i>
          <div class="text">{{ $name }} <b>x{{ $amount }}</b></div>
     </div>
@endforeach

For some reason, if i print $name alone, it shows the number (2) that should be printed while using the $amount variable.

出于某种原因,如果我单独打印 $name,它会显示在使用 $amount 变量时应该打印的数字 (2)。

Is there any way to solve my problem?

有什么办法可以解决我的问题吗?

采纳答案by koalaok

If $post->loot->content contains [{"Item":2}]

如果 $post->loot->content 包含 [{"Item":2}]

It is an array of objects so, your $amount is the whole {"Item":2}, not 2.

它是一个对象数组,因此您的 $amount 是整个 {"Item":2},而不是 2。

so the loop can be something like:

所以循环可以是这样的:

@foreach ($post->loot->content as $id=>$json)
    @php
        $obj =json_decode($json, true)
    @endphp
    @foreach ($obj as $key=>$val)
     <div class="item">
          <i class="fab fa-cuttlefish"></i>
          <div class="text">{{ $key }} <b>x{{ $val }}</b></div>
     </div>
     @endforeach
@endforeach

Not sure what you need but maybe you can swap

不确定你需要什么,但也许你可以交换

 <div class="text">{{ $key }} <b>x{{ $val }}</b></div>

with

   <div class="text">{{ $id }} <b>x{{ $val }}</b></div>

If you need the index of the whole object in the list instead of the attribute's obj key.

如果您需要列表中整个对象的索引而不是属性的 obj 键。