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 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?