使用implode时,数组到字符串转换错误

Fra*_*sca 20 php arrays string implode

我对我正在陈述的错误感到困惑 Array to string conversion

我很困惑的原因是我正在努力做到这一点,将数组转换为字符串,implode根据手册应该允许我将我的数组转换为字符串.那我为什么会收到错误?

var $matches是一个数组.$error_c是我想要存储字符串的var.

print_r($matches); // prints the array correctly
$error_c = implode(',', $matches);
echo $error_c;
Run Code Online (Sandbox Code Playgroud)

输出简单array并给出:

Notice: Array to string conversion in ...
Run Code Online (Sandbox Code Playgroud)

手册说明了implode — Join array elements with a string为什么我尝试这样做时会出错?

编辑:这是我得到的输出 $matches

Array ( [0] => Array ( [0] => C [1] => E [2] => R [3] => R [4] => O [5] => R [6] => C [7] => O [8] => N [9] => T [10] => A [11] => C [12] => T [13] => S [14] => U [15] => P [16] => P [17] => R [18] => E [19] => S [20] => S [21] => E [22] => D ) ) 
Run Code Online (Sandbox Code Playgroud)

小智 29

你有一个数组数组...试试这个:

$error_c = implode(',', $matches[0]);
Run Code Online (Sandbox Code Playgroud)


Mad*_*gle 9

$error_c = implode(',', $matches[0]);
echo $error_c;
Run Code Online (Sandbox Code Playgroud)

因为你的array包含arrays


Yve*_*ndo 6

该问题是由于您调用的implodeArray二维的。

Array ( 
    [0] => Array ( 
        [0] => C 
        [1] => E 
        [2] => R 
        [3] => R 
        [4] => O 
        [5] => R 
        [6] => C 
        [7] => O 
        [8] => N 
        [9] => T 
        [10] => A 
        // ...
    ) 
) 
Run Code Online (Sandbox Code Playgroud)

这相当于

[["C", "E", "R", "R", "O", "R", "C", "O", "N", "..." ]]
Run Code Online (Sandbox Code Playgroud)

在执行内爆之前您应该做的是展平数组,之后您可以implode使用展平的数组进行调用,或者仅使用主数组中的第一项(即数组)调用内爆。

这是一个为展平数组提供指导的问题 如何展平多维数组?

使用允许展平数组的函数,您可以像这样执行调用

implode(flatten($array_of_data), $matches);
Run Code Online (Sandbox Code Playgroud)

无需仅访问第一项,无论数组中有多少项, $matchesflatten函数都将返回一个一维数组,您可以在其上调用implode