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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!