开发者

Implode and Explode Multi dimensional arrays [duplicate]

开发者 https://www.devze.com 2023-01-19 04:39 出处:网络
This question already has answers here: Return single column from a multi-dimensional array [duplicate]
This question already has answers here: Return single column from a multi-dimensional array [duplicate] 开发者_Go百科 (7 answers) Closed 9 years ago.

Are there any functions for recursively exploding and imploding multi-dimensional arrays in PHP?


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_query among others.


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.

http://www.php.net/manual/en/function.var-export.php


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.


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).

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消