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

$type = $_POST[type];

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

Sports|Festivals|Other

当前回答

对于存储关联数组,您可以使用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);

其他回答

$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");

$string_array = json_encode($data);

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

最好的方法之一:

echo print_r($array, true);

这个保存键和值

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
$string = implode('|',$types);

然而,Incognito是正确的,您可能不想以这种方式存储它——这完全浪费了数据库的关系功能。

如果执意要序列化,还可以考虑使用json_encode()