This article mainly introduces the PHP implementation of the two-dimensional associative array into a string method, involving the PHP array recursive traversal, conversion, de-weight, splicing and other related operations skills, the need for friends can refer to the next
Specific as follows:
Demand
The project encountered the problem of two-dimensional associative array-to-string, consulted the relevant data, wrote the following procedures, and can filter the duplicate keywords.
For example, PHP's two-dimensional array is as follows:
$name = Array ( "self" = "Wangzhengyi", "student" = = Array ( "Chenshan", "Xiaolingang" ), "Unkmow" = "Chaikun", "teacher" = = Array ( "Huangwei", "fanwenqing" ));
The last string format to get is:
Wangzhengyi,chenshan,xiaolingang,chaikun,huangwei,fanwenqing
Ideas
Method
Use the static keyword and recursive ideas to iterate through the array
Custom Function Code (PHP)
function Arrtostr ($array) { //defines an array that stores all strings static $r _arr = Array (); if (Is_array ($array)) { foreach ($array as $key = + $value) { if (Is_array ($value)) { //recursive traversal arrtostr ( $value); } else { $r _arr[] = $value; } } } else if (is_string ($array)) { $r _arr[] = $array; } Array de -weight $r _arr = Array_unique ($r _arr); $string = Implode (",", $r _arr); return $string;}
Complete Sample code:
<?php$name = Array ( "self" = "Wangzhengyi", "student" = = Array ( "Chenshan", "Xiaolingang" ), "Unkmow" = "Chaikun", "teacher" = = Array ( "Huangwei", "fanwenqing" ); function Arrtostr ($array) { //defines an array that stores all strings static $r _arr = Array (); if (Is_array ($array)) { foreach ($array as $key = + $value) { if (Is_array ($value)) { //recursive traversal Arrto STR ($value); } else { $r _arr[] = $value; } } } else if (is_string ($array)) { $r _arr[] = $array; } Array de -weight $r _arr = Array_unique ($r _arr); $string = Implode (",", $r _arr); return $string;} echo Arrtostr ($name);? >
Operation Result:
Wangzhengyi,chenshan,xiaolingang,chaikun,huangwei,fanwenqing
Related recommendations:
What are the ways PHP implements multidimensional array sorting algorithms
Procedure for manipulating PHP associative arrays and indexed arrays
How to do php reset array to continuous numeric index