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

$type = $_POST[type];

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

Sports|Festivals|Other

当前回答

你可以使用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

其他回答

这个保存键和值

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;
}

希望它能帮助到别人。

对于存储关联数组,您可以使用serialize:

$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

file_put_contents('stored-array.txt', serialize($arr));

并使用unserialize加载:

$arr = unserialize(file_get_contents('stored-array.txt'));

print_r($arr);

但是如果需要用数组创建动态的.php文件(例如配置文件),你可以使用var_export(…,正确);,像这样:

保存于文件:

$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

$str = preg_replace('#,(\s+|)\)#', '$1)', var_export($arr, true));
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';

file_put_contents('config.php', $str);

获取数组值:

$arr = include 'config.php';

print_r($arr);

还有另一种方法,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;
}

在这里拍摄的。

使用内爆

implode("|",$type);
json_encode($data) //converts an array to JSON string
json_decode($jsonString) //converts json string to php array

为什么JSON:你可以在大多数编程语言中使用它,由php的serialize()函数创建的字符串仅在php中可读,并且你不喜欢将这些东西存储在你的数据库中,特别是如果数据库在用不同编程语言编写的应用程序之间共享