PHP - Multidimensional array to CSV

后端 未结 3 1902
情深已故
情深已故 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:36

    Not sure if this will help you, but would it not be easier to flatten the array first and then format in in the way you want? To flatten the array try this:

    $array = "YOUR ARRAY";
    
    $FlatArray = array();
    
    foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $k=>$v)
      {
        $FlatArray[$k] = $v;
      }
    

    Been trying all morning to come up with a recursive function for this. This is as close as I got, Maybe you can improve upon this.

    $data = array('name' =>array('singular' => NULL,'plural' => NULL,'fields' =>array('price' =>array('label' =>'Preis','company_id' =>array('label' => NULL,'placeholder' => NULL)))));
    
    
    function arr_to_csv($data,$csv = '||')
    {
    $list = "";
    foreach($data as $key => &$value)
            {
            $list .= $key . $csv .((!is_array($value))?(is_null($value)?'null':$value): arr_to_csv($value))."
    "; } return $list; } print_r(arr_to_csv($data));

    Returns This:

    name||singular||null
    
    plural||null
    
    fields||price||label||Preis
    
    company_id||label||null
    
    placeholder||null
    

提交回复
热议问题