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

$type = $_POST[type];

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

Sports|Festivals|Other

当前回答

内爆():

<?php
$string = implode('|',$types);

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

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

其他回答

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

您可以使用json_encode()

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

稍后只需使用json_decode()来解码来自DB的字符串。 其他任何东西都是无用的,JSON保持数组关系的完整性,以供以后使用!

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

$string_array = json_encode($data);

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

最好的方法之一:

echo print_r($array, true);

内爆():

<?php
$string = implode('|',$types);

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

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