PHP中的Array2String & String2Array

来源:互联网 发布:全球域名注册量排名 编辑:程序博客网 时间:2024/06/01 22:02

在用PHP开发时我们有时期望将一个数组(任意多维),在页面之间传递或者存入数据库。这时我们可以将Array转换为String传递或保存,取出用的时候在转换回来即可。

<?php/*在Array和String类型之间转换,转换为字符串的数组可以直接在URL上传递*/// convert a multidimensional array to url save and encoded string// usage: string Array2String( array Array )function Array2String($Array){    $Return='';    $NullValue="^^^";    foreach ($Array as $Key => $Value) {        if(is_array($Value))            $ReturnValue='^^array^'.Array2String($Value);        else            $ReturnValue=(strlen($Value)>0)?$Value:$NullValue;        $Return.=urlencode(base64_encode($Key)) . '|' . urlencode(base64_encode($ReturnValue)).'||';    }    return urlencode(substr($Return,0,-2));}// convert a string generated with Array2String() back to the original (multidimensional) array// usage: array String2Array ( string String)function String2Array($String){    $Return=array();    $String=urldecode($String);    $TempArray=explode('||',$String);    $NullValue=urlencode(base64_encode("^^^"));    foreach ($TempArray as $TempValue) {        list($Key,$Value)=explode('|',$TempValue);        $DecodedKey=base64_decode(urldecode($Key));        if($Value!=$NullValue) {            $ReturnValue=base64_decode(urldecode($Value));            if(substr($ReturnValue,0,8)=='^^array^')                $ReturnValue=String2Array(substr($ReturnValue,8));            $Return[$DecodedKey]=$ReturnValue;        }        else        $Return[$DecodedKey]=NULL;    }    return $Return;}?>



0 0
原创粉丝点击