doubao6681 2019-04-09 14: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 15: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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?