将PHP数组转换为字符串的最佳方法是什么? 我有变量$type,它是一个类型数组。

$type = $_POST[type];

我想把它作为一个单独的字符串存储在我的数据库中,每个条目由|分隔:

Sports|Festivals|Other

当前回答

如果你有一个数组(比如$_POST),并且需要保存键和值:

function array_to_string($array) {
   foreach ($array as $a=>$b) $c[]=$a.'='.$b;
   return implode(', ',$c);
}

结果是:“名字=保罗,年龄=23,城市=芝加哥”

其他回答

这个保存键和值

function array2string($data){
    $log_a = "";
    foreach ($data as $key => $value) {
        if(is_array($value))    $log_a .= "[".$key."] => (". array2string($value). ") \n";
        else                    $log_a .= "[".$key."] => ".$value."\n";
    }
    return $log_a;
}

希望它能帮助到别人。

最好的方法之一:

echo print_r($array, true);

你可以使用serialize:

$array = array('text' => 'Hello world', 'value' => 100);
$string = serialize($array); // a:2:{s:4:"text";s:11:"Hello world";s:5:"value";i:100;}

并使用unserialize将字符串转换为数组:

$string = 'a:2:{s:4:"text";s:11:"Hello world";s:5:"value";i:100;}';
$array = unserialize($string); // 'text' => 'Hello world', 'value' => 100
$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");

$string_array = json_encode($data);

现在您可以将这个$string_array值插入到数据库中

还有另一种方法,PHP var_export()与短数组语法(方括号)缩进4个空格:

function varExport($expression, $return = true) {
    $export = var_export($expression, true);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [null, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    
    if ((bool) $return) return $export; else echo $export;
}

在这里拍摄的。