举例,php的二维数组如下:

$name = array( "self" => "wangzhengyi", "student" => array( "chenshan", "xiaolingang" ), "unkmow" => "chaikun", "teacher" => array( "huangwei", "fanwenqing" ) );

最后要获得的string格式是:

wangzhengyi,chenshan,xiaolingang,chaikun,huangwei,fanwenqing

思路

方法

利用static关键字和递归的思想去遍历数组

自定义函数代码(php)

function arrToStr ($array) { // 定义存储所有字符串的数组 static $r_arr = array(); if (is_array($array)) { foreach ($array as $key => $value) { if (is_array($value)) { // 递归遍历 arrToStr($value); } else { $r_arr[] = $value; } } } else if (is_string($array)) { $r_arr[] = $array; } //数组去重 $r_arr = array_unique($r_arr); $string = implode(",", $r_arr); return $string; }

完整示例代码:

<?php $name = array( "self" => "wangzhengyi", "student" => array( "chenshan", "xiaolingang" ), "unkmow" => "chaikun", "teacher" => array( "huangwei", "fanwenqing" ) ); function arrToStr ($array) { // 定义存储所有字符串的数组 static $r_arr = array(); if (is_array($array)) { foreach ($array as $key => $value) { if (is_array($value)) { // 递归遍历 arrToStr($value); } else { $r_arr[] = $value; } } } else if (is_string($array)) { $r_arr[] = $array; } //数组去重 $r_arr = array_unique($r_arr); $string = implode(",", $r_arr); return $string; } echo arrToStr($name); ?>

运行结果:

wangzhengyi,chenshan,xiaolingang,chaikun,huangwei,fanwenqing相关推荐:

PHP实现多维数组排序算法有哪些方式

操作php关联数组与索引数组步骤详解

怎样做到php重置数组为连续数字索引