将PHP数组转换为字符串的最佳方法是什么? 我有变量$type,它是一个类型数组。
$type = $_POST[type];
我想把它作为一个单独的字符串存储在我的数据库中,每个条目由|分隔:
Sports|Festivals|Other
将PHP数组转换为字符串的最佳方法是什么? 我有变量$type,它是一个类型数组。
$type = $_POST[type];
我想把它作为一个单独的字符串存储在我的数据库中,每个条目由|分隔:
Sports|Festivals|Other
当前回答
您可以使用json_encode()
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
稍后只需使用json_decode()来解码来自DB的字符串。 其他任何东西都是无用的,JSON保持数组关系的完整性,以供以后使用!
其他回答
最好的方法之一:
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;
}
希望它能帮助到别人。
内爆():
<?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
有很多方法,
最好的两种方法是
$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