doubao6681 2019-04-09 06:16
浏览 95
已采纳

继续获取“数组到字符串转换”尝试运行连接方法时出错

So I'm working on a problem where I need to convert an array of values into a string so that it can be displayed for an excel document. But I keep on getting an "Array to string conversion" error when I try to run the export. The code is

$counties = "";
if(isset($forms->form_info['county'])){
  for($i = 0; $i < count($forms->form_info['county']); $i++){
    if(is_int($i / 10) && $i != 0){
      $counties .= $forms->form_info['county'][$i] . ",
";
    } elseif($i == (count($forms->form_info['county']) - 1)) {
      // Keep getting the error on the line below
      $counties .= $forms->form_info['county'][$i] . " ";
    } else {
      $counties .= $forms->form_info['county'][$i] . ", ";
    }
  }
}

I've done a dd of a gettype on counties as well as the form element I'm trying to use, and both appeared as strings, so I'm lost on where the supposed array that's being converted is. I've tried making $form->form_info['county'][$i] into its own variable and concatenating it to the counties variable but received the same issue.

The result of dd($forms->form_info['county'][$i]); is

"Bernalillo County"

The result of dd($forms->form_info['county']); is

array:1 [▼
   0 => "Bernalillo County"
]

The result of a dd(var_dump($forms->form_info['county'][$i])); is

string(17) "Bernalillo County"
null

And here is the direct screenshot of the issue

Php error screen

展开全部

  • 写回答

3条回答 默认 最新

  • douyeke2695 2019-04-09 07:45
    关注

    Obviously the data is not what you expect, but this code is very verbose for what you're trying to do: separate the array values with commas, putting a line break after every tenth element. We can do that easily with use of array_chunk.

    <?php
    $data = str_split("abcdefghijklmnopqrstuvwxyz");
    $output = "";
    
    foreach(array_chunk($data, 10) as $v) {
        $output .= implode(", ", $v) . ",
    ";
    }
    // get rid of that final comma space
    echo substr($output, 0, -2);
    

    Output:

    a, b, c, d, e, f, g, h, i, j,
    k, l, m, n, o, p, q, r, s, t,
    u, v, w, x, y, z
    

    Adapting to your code:

    $counties = "";
    if(isset($forms->form_info['county'])){
        foreach(array_chunk($forms->form_info['county'], 10) as $v) {
            $counties .= implode(", ", $v) . ",
    ";
        }
        $counties = substr($counties, 0, -2);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部