php 内爆和分解多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3899971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implode and Explode Multi dimensional arrays
提问by HyderA
Are there any functions for recursively exploding and imploding multi-dimensional arrays in PHP?
PHP 中是否有递归爆炸和内爆多维数组的函数?
回答by lonesomeday
You can do this by writing a recursive function:
您可以通过编写递归函数来做到这一点:
function multi_implode($array, $glue) {
$ret = '';
foreach ($array as $item) {
if (is_array($item)) {
$ret .= multi_implode($item, $glue) . $glue;
} else {
$ret .= $item . $glue;
}
}
$ret = substr($ret, 0, 0-strlen($glue));
return $ret;
}
As for exploding, this is impossible unless you give some kind of formal structure to the string, in which case you are into the realm of serialisation, for which functions already exist: serialize, json_encode, http_build_queryamong others.
至于爆炸,除非您为字符串提供某种形式的结构,否则这是不可能的,在这种情况下,您将进入序列化领域,其功能已经存在:serialize,json_encode,http_build_query等。
回答by Dave
I've found that var_export is good if you need a readable string representation (exploding) of the multi-dimensional array without automatically printing the value like var_dump.
我发现如果您需要多维数组的可读字符串表示(爆炸)而不像 var_dump 那样自动打印值,那么 var_export 是很好的。
回答by Gumbo
You can use array_walk_recursive
to call a given function on every value in the array recursively. How that function looks like depends on the actual data and what you're trying to do.
您可以使用array_walk_recursive
递归调用数组中每个值的给定函数。该函数的外观取决于实际数据和您要执行的操作。
回答by Falk
I made two recursive functions to implode and explode.
The result of multi_explode
may not work as expected (the values are all stored at the same dimension level).
我做了两个递归函数来内爆和爆炸。的结果multi_explode
可能无法按预期工作(所有值都存储在同一维度级别)。
function multi_implode(array $glues, array $array){
$out = "";
$g = array_shift($glues);
$c = count($array);
$i = 0;
foreach ($array as $val){
if (is_array($val)){
$out .= multi_implode($glues,$val);
} else {
$out .= (string)$val;
}
$i++;
if ($i<$c){
$out .= $g;
}
}
return $out;
}
function multi_explode(array $delimiter,$string){
$d = array_shift($delimiter);
if ($d!=NULL){
$tmp = explode($d,$string);
foreach ($tmp as $key => $o){
$out[$key] = multi_explode($delimiter,$o);
}
} else {
return $string;
}
return $out;
}
To use them:
要使用它们:
echo $s = multi_implode(
array(';',',','-'),
array(
'a',
array(10),
array(10,20),
array(
10,
array('s','t'),
array('z','g')
)
)
);
$a= multi_explode(array(';',',','-'),$s);
var_export($a);