将PHP数组转换为字符串的最佳方法是什么? 我有变量$type,它是一个类型数组。
$type = $_POST[type];
我想把它作为一个单独的字符串存储在我的数据库中,每个条目由|分隔:
Sports|Festivals|Other
将PHP数组转换为字符串的最佳方法是什么? 我有变量$type,它是一个类型数组。
$type = $_POST[type];
我想把它作为一个单独的字符串存储在我的数据库中,每个条目由|分隔:
Sports|Festivals|Other
当前回答
json_encode($data) //converts an array to JSON string
json_decode($jsonString) //converts json string to php array
为什么JSON:你可以在大多数编程语言中使用它,由php的serialize()函数创建的字符串仅在php中可读,并且你不喜欢将这些东西存储在你的数据库中,特别是如果数据库在用不同编程语言编写的应用程序之间共享
其他回答
内爆():
<?php
$string = implode('|',$types);
然而,Incognito是正确的,您可能不想以这种方式存储它——这完全浪费了数据库的关系功能。
如果执意要序列化,还可以考虑使用json_encode()
有很多方法,
最好的两种方法是
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
//ouputs as
{"a":1,"b":2,"c":3,"d":4,"e":5}
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r
$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");
$string_array = json_encode($data);
现在您可以将这个$string_array值插入到数据库中
最好的方法之一:
echo print_r($array, true);
还有另一种方法,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;
}
在这里拍摄的。