htmlspecialchars期望参数1为字符串,给定数组 [英] htmlspecialchars expects parameter 1 to be string, array given

查看:91
本文介绍了htmlspecialchars期望参数1为字符串,给定数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在blade.php视图上打印模型内容时遇到下一个错误:

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

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

此模型"content"是表中的一列(json类型),看起来像这样:

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

[{"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

由于某种原因,如果我仅打印$ name,它会显示在使用$ amount变量时应打印的数字(2).

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

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

Is there any way to solve my problem?

推荐答案

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

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

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

It is an array of objects so, your $amount is the whole {"Item":2}, not 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>

使用

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

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

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

这篇关于htmlspecialchars期望参数1为字符串,给定数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆