Laravel - htmlspecialchars()期望参数1为字符串,给定对象

Kid*_*ddo 14 php laravel

我去了这个错误:

htmlspecialchars() expects parameter 1 to be string, object given
Run Code Online (Sandbox Code Playgroud)

我在控制器中使用:

$data = '{"pr":{"code":"1"},"ac":[[{"icon":"web","action":"link","url":"asd"}]]}'
$newData = json_decode($data);
Run Code Online (Sandbox Code Playgroud)

我将它作为数组发送到视图:'data'=> $ newData当我尝试在视图中使用$ data时,它会给我这个错误

尝试使用$ data-> ac OR $ data ['ac']但仍然相同......请帮忙吗?

jfa*_*ich 22

使用刀片回波时{{ $data }},它将自动转义输出.它只能逃脱字符串.在您的数据中$data->ac是一个数组并且$data是一个对象,它们都不能按原样回显.您需要更具体地说明如何输出数据.究竟是什么样的完全取决于你想要完成的事情.例如,要显示您需要执行的链接{{ $data->ac[0][0]['url'] }}(不确定为什么您有两个嵌套数组,但我只是关注您的数据结构).

@foreach($data->ac['0'] as $link)
    <a href="{{ $link['url'] }}">This is a link</a>
@endforeach
Run Code Online (Sandbox Code Playgroud)


小智 8

如果您打算将整个数组从html发送到控制器,则可以使用以下方法:

从blade.php:

 <input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}"> 
Run Code Online (Sandbox Code Playgroud)

在控制器中

    public function Get(Request $req) {

    $quotation = array('quotation' => json_decode($req->quotation));

    //or

    return view('quotation')->with('quotation',json_decode($req->quotation))


}
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以用 serialize

<input type="hidden" name="quotation[]" value="{{serialize($quotation)}}">
Run Code Online (Sandbox Code Playgroud)

但是在这种情况下,最好的json_encode方法是在刀片和json_decode控制器中使用该方法。