把一个一维或多维的数组连接成一个字符串-php面试题-算法

自定义一个函数 ,把一个数组变成用,(逗号)连接起来的字符串 (注意:应考虑到多维数组的情况,并以返回值的形式返回)

<?php
/*
*  ————————————————-
*   @file        : 5.php
*   @function    : arr2str
*   @link        : 星模PHP培训 www.xingmo.com
*   @copyright    : 2002-2009 Xingmo Inc
*   @author        : Fanglor <fanglor#163.com>
*   @date        : 2010-06-25
*   @update        :
*  ————————————————-
*/

$fruits = array (
“fruits”  => array(“a” => “orange”, “b” => “banana”, “c” => “apple”),
“numbers” => array(1, 2, 3, 4, 5, 6),
“holes”   => array(“first”, 5 => “second”, “third”)
);
$arr1 = array(1, 2, 3, 4, 5, 6=>’fanglor’);

function arr2str ($arr)
{
static $res_arr = array();
if (is_array ($arr))
{
foreach ($arr as $key => $val )
{
if (is_array($val))
{
arr2str ($val);
}
else
{
$res_arr[] = $val;
}
}
}
elseif (is_string ($arr))
{
$res_arr[] = $arr;
}
return implode(‘,’,$res_arr);
}

$str = arr2str ($arr1);
print_r ($str);
?>


Leave Your Comment

Your email will not be published or shared. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

*
请输入图片中的字符以验证你并非垃圾机器人. 点击图片收听验证码的语音版.
点击这里收听此验证码的语音版本