Home >php教程 >PHP源码 >数组值拼接成字符串

数组值拼接成字符串

PHP中文网
PHP中文网Original
2016-05-25 17:14:221309browse

数组值拼接成字符串            

将所有数组值拼接成一个字符串 
php自带的 implode 将数组拼接成一个字符串,这个方法有一个不足就是,数组的值不能是数组 只能是字符或者数字之类的基本类型 ,如果数组中的值也是一个数组的话,那么将会转换失败 。我在实际项目中遇到过这的需求,今天把我写好的代码分享给大家。希望,对需要的朋友有所帮助。 
不足之处,敬请包涵。

<?php
class Convert 
{
    public static  function arrayConvertString( $array ,$join )
    {
        $result = "" ;
         
        foreach ( $array  as $k => $v )
        {
            if( is_array( $v ) )
            {
                $result .= $join. self::arrayConvertString( $v , $join ) ;
            }
            else
            {
                $result .= $join . $v ;
            }
            $result = preg_replace( "~^" . $join . "~" , "", $result ) ;
        }
         
        return $result ;
    }
}
// test
$array = array( array(1,2,3,4,5),array("x1","x2","x3","x4","x5") ) ;
$str = Convert::arrayConvertString( $array , ",") ;
echo $str ;
// echo:1,2,3,4,5,x1,x2,x3,x4,x5
?>

 以上就是数组值拼接成字符串的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
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