【问题标题】:ErrorException : Array to string conversion in PHPErrorException:PHP 中的数组到字符串的转换
【发布时间】:2018-08-04 19:43:36
【问题描述】:

我想在 Laravel 中将数组转换为字符串。我已经搜索并实现了 implode() 函数来转换它,但得到了这个错误

ErrorException (E_NOTICE) Array to string conversion

这是我在控制器中的代码

$sliderImageDataArray[] =array(
                "title"=> $value->title,
                "text"=> "<p><span id=\"hs_cos_wrapper_module_1498510869515998\" class=\"hs_cos_wrapper hs_cos_wrapper_widget_container hs_cos_wrapper_type_widget_container\" data-hs-cos-general-type=\"widget_container\" data-hs-cos-type=\"widget_container\">".$value->text."<\/span><\/p>\n<p><a class=\"btn  btn-secondary\" href=\"http://localhost/sencare/book-appoinment/\" target=\"_self\">  Make An Appointment <\/a>\u00a0<a class=\"btn  btn-light\" href=\"http://localhost/sencare/our-doctors/\" target=\"_self\"> Our Doctors<\/a><\/p>\n",
                "is_video"=> false,
            );

$sliderImageDataArray = implode(" ",$sliderImageDataArray);

return $sliderImageDataArray;

请大家帮忙

【问题讨论】:

  • 如果您不发布代码,我们将无法帮助您。
  • @ishegg .....我已经更新了我的帖子。请检查

标签: php arrays string html


【解决方案1】:

使用以下代码

{!! str_replace("'", "\'", json_encode($sliderImageDataArray)) !!};

而不是

$sliderImageDataArray = implode(" ",$sliderImageDataArray);

【讨论】:

    【解决方案2】:

    注意$sliderImageDataArray 后面的[]。您实际上是在将具有这些值的数组分配给数组的 第一个元素,即$sliderImageDataArray。所以,implode() 实际上试图通过那个数组加入,而不是里面的那个。由于生成的片段是一个数组,而不是一个字符串,它会给你Array to string conversion 错误。删除[]:

    <?php
    $sliderImageDataArray =array(
                    "title"=> "test title",
                    "text"=> "<p><span id=\"hs_cos_wrapper_module_1498510869515998\" class=\"hs_cos_wrapper hs_cos_wrapper_widget_container hs_cos_wrapper_type_widget_container\" data-hs-cos-general-type=\"widget_container\" data-hs-cos-type=\"widget_container\">value<\/span><\/p>\n<p><a class=\"btn  btn-secondary\" href=\"http://localhost/sencare/book-appoinment/\" target=\"_self\">  Make An Appointment <\/a>\u00a0<a class=\"btn  btn-light\" href=\"http://localhost/sencare/our-doctors/\" target=\"_self\"> Our Doctors<\/a><\/p>\n",
                    "is_video"=> false,
                );
    
    $sliderImageDataArray = implode(" ",$sliderImageDataArray);
    
    echo $sliderImageDataArray;
    

    而且它工作正常。

    Demo

    【讨论】:

    • 我有一堆从数据库中获取的数据,需要将它们保存为数组格式并将它们发送到视图。这就是我在sliderImageDataArray 中使用[] 的原因。
    • 我明白了,但是implode() 不能加入arrays。您需要循环 $sliderImageDataArray 和 foreach() 并单独内爆每个元素。
    • @ishegg .....请看这篇文章 [stackoverflow.com/questions/48970613/…
    • 哦,对不起,我的朋友还没有在这里给出答案......是的......这是答案......{!! str_replace("'", "\'", json_encode($sliderImageDataArray)) !!};
    猜你喜欢
    • 2019-09-20
    • 2011-03-25
    • 2017-10-27
    • 2015-02-21
    • 1970-01-01
    相关资源
    最近更新 更多