Multidimensional Array to String

后端 未结 7 633
挽巷
挽巷 2020-12-03 11:59

I am trying to convert a multidimensional array into a string with a particular format.

function convert_multi_array($array) {
    foreach($array as $value)          


        
7条回答
  •  不知归路
    2020-12-03 12:25

    You also can just take the original implementation from the PHP join manual (http://php.net/manual/en/function.join.php)

    function joinr($join, $value, $lvl=0)
    {
        if (!is_array($join)) return joinr(array($join), $value, $lvl);
        $res = array();
        if (is_array($value)&&sizeof($value)&&is_array(current($value))) { // Is value are array of sub-arrays?
            foreach($value as $val)
                $res[] = joinr($join, $val, $lvl+1);
        }
        elseif(is_array($value)) {
            $res = $value;
        }
        else $res[] = $value;
        return join(isset($join[$lvl])?$join[$lvl]:"", $res);
    }
    
    $arr = array(array("blue", "red", "green"), array("one", "three", "twenty"));
    joinr(array("&", "~"), $arr);
    

    This is recursive, so you even can do

    $arr = array(array("a", "b"), array(array("c", "d"), array("e", "f")), "g");
    joinr(array("/", "-", "+"), $arr);
    

    and you'll get

    a-b/c+d-e+f/g
    

提交回复
热议问题