PHP - Multidimensional array to CSV

后端 未结 3 1900
情深已故
情深已故 2020-12-12 03:20

I currently have coded a way to turn a multidimensional array to comma separated values (I\'m using pipes instead of commas for ease of debugging). The problem is, I know th

3条回答
  •  情歌与酒
    2020-12-12 03:48

    This is some pseudocode, but it is a start:

    $strings = [];
    $flattenArray = function($arr, $level) use (&$strings, &$flattenArray) {
    
        foreach($arr as $key=>$value){
            $s = &$strings[$level];
            if(!isset($s)) { $s = array(); }
            $s[] = $key;
            if(is_array($value)) {
               $flattenArray($value, $level);
            }
            else {
               $s[] = $value;
            }
            $level ++;
        }
    };
    $flattenArray($myArray, 0);
    foreach($strings as &$arr) {
         $arr = implode("||", $arr);
    }
    

    Small demo with your array: http://codepad.viper-7.com/CR2SPY <-- It does not work fully, but it is a start


    Update:

    Here is a demo that I think works the way you want: http://codepad.viper-7.com/shN4pH

    Code:

    $strings = [];
    $flattenArray = function($arr, $level, $k = null) use (&$strings, &$flattenArray) {
    
        foreach($arr as $key=>$value){
            if($k === null) {
                $s = &$strings[$key];
            }
            else {
                $s = &$strings[$k];
            }
            if(!isset($s)) { 
                $s = array();  
            }
            $str = &$s[$level];
            if(!isset($str)) { 
                $str = array(); 
                
                if($k !== null) { $str[] = $k; }
            }
            $str[] = $key;
            if(is_array($value)) {
               $flattenArray($value, $level, ($k === null) ? $key : $k);
            }
            else {
                $str[] = is_null($value) ? "null" : $value;
            }
            $level ++;
        }
    };
    $flattenArray($myArray, 0);
    $all = [];
    foreach($strings as $k => $arr){
        $new = array();
        foreach($arr as $ky => $ar) {
            $all[] = implode("||", $ar);
        }
    }
    
    print_r($all);
    

提交回复
热议问题