Home > php教程 > PHP源码 > body text

PHP数组转字符串写入数据库的方法

WBOY
Release: 2016-06-08 17:22:33
Original
1856 people have browsed it

下面本文章总结了三种把数组转换成字符串然后写入到数据库中,一是直接利用implode函数,另外就使用serialize与eval函数进行转换,下面来一起看看吧。

<script>ec(2);</script>

最简单的办法

转换implode

 代码如下 复制代码

数组->字符
$txt=implode("?",arr[]);

字符->数组
$arr[]=explode("?",txt);

使用php的serialize函数。

例子:

 代码如下 复制代码

$data = array('上海', '北京', '武汉');
$data = serialize($data);
echo $data;

如何再将从数据库中取出的数组字符串,转换成数组呢?用unserialize函数:

 代码如下 复制代码
$data = unserialize($data);
echo $data;

 
当然这样我们还可以直接写入到文件中

serialize和反序列unserialize来实现。

 代码如下 复制代码

$file="./data/file.cache";
$array = array("count" => "3000",
              "num"  =>"300");
 //缓存
file_put_contents($file,serialize($array));//写入缓存
$cacheArray = unserialize(file_get_contents($file));
print_r($cacheArray);
?>

例子

使用期php的eval函数

string2array,array2string PHP数组转字符串写入数据库,字符串数组转可执行

 代码如下 复制代码

/**
* 将字符串转换为数组
*
* @param    string  $data   字符串
* @return   array   返回数组格式,如果,data为空,则返回空数组
*/ 
 function string2array($data) {  
    if($data == '') return array();  
    @eval("$array = $data;");  
    return $array;  
}  
 /**
* 将数组转换为字符串
*
* @param    array   $data       数组
* @param    bool    $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @return   string  返回字符串,如果,data为空,则返回空
*/ 
function array2string($data, $isformdata = 1) {  
    if($data == '') return '';  
    if($isformdata) $data = new_stripslashes($data);  
    return addslashes(var_export($data, TRUE));  

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!