PHP将索引数组导出为CSV

时间:2016-10-13 14:04:32

标签: php csv

我有一个以下索引数组

$export_data = array (
  [0] => 1,
  [1] => 2,
  [2] => 3,
  [3] => 4,
  [4] => 5,
  [8] => 9,
  [9] => 10,
);

我知道如何使用fputcsv将其导出到csv。但是我的问题是我需要将数据导出到正确的列中,即$ export_data [8]中的值需要在第9列而不是第6列中导出。

请问这怎么办?

3 个答案:

答案 0 :(得分:2)

如果我理解正确,你想在数据之间放置空闲列,所以键与列号匹配。

$arr = array(
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 4,
    4 => 5,
    8 => 9,
    9 => 10,
);

$csvArray = array();
$maxKey = max(array_keys($arr));
for($i = 0; $i <= $maxKey; $i++){
    if(array_key_exists($i, $arr)){
        $csvArray[$i] = $arr[$i];
    } else {
        $csvArray[$i] = null;
    }
}
print_r($csvArray);

演示:live demo

来描述它,只需循环遍历数组并检查是否设置了密钥,如果是,则将其值赋值给下一个数组,如果不是,则赋值为null

优化

$csvArray = array();
$maxKey = max(array_keys($arr));
// ++$i is microscopically faster when going for the long haul; such as 10,000,000 iterations
// Try it for yourself:
// $start = microtime(true);
// for($i=0; $i<10000000; $i++){}
// echo (microtime(true) - $start).' seconds';
for($i = 0; $i <= $maxKey; ++$i){
    // we can use isset() because it returns false if the value is null anyways. It is much faster than array_key_exists()
    $csvArray[$i] = (isset($arr[$i]) ? $arr[$i] : null);
}

答案 1 :(得分:2)

你去,老板。

$export_data = array_replace(array_map(function($v){return null;}, range(0, max(array_keys($export_data)))), $export_data);

测试100,000次迭代,结果以秒为单位:

Version     Run1  Run2  Run3
PHP 5.6.20  .58   .55   .50
PHP 7.0.5   .18   .21   .21

现在为了解释,所以我不会被down down or or或被指控为巫术。

$export_data = array (
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 4,
    4 => 5,
    8 => 9,
    9 => 10,
);

$export_data = 
    array_replace( // replace the elements of the 10-item array with your original array and the filled-in blanks are going to be null. I did not use array_merge() because it would append $export_data onto our dynamic range() array rather than replacing elements as needed.
        array_map( // loop the 10-item array and apply the declared function per element. This function ends up returning the 10-item array with all keys intact but the values will be null
            function($v){return null; /* return ''; // if you prefer and empty string instead of null*/}, // set each value of the 10-item array to null
            range( // create an 10-item array with indexes and values of 0-9
                0,
                max(array_keys($export_data)) // get the highest key of your array which is 9
            )
        ),
        $export_data // your original array with gaps
    );

var_dump($export_data);
print_r($export_data);

答案 2 :(得分:-1)

我只是用空列的空值完全填充数组:

$export_data = array (
  [0] => 1,
  [1] => 2,
  [2] => 3,
  [3] => 4,
  [4] => 5,
  [5] => '',
  [6] => '',
  [7] => '',
  [8] => 9,
  [9] => 10,
);

没有索引(因为它们在任何情况下都是自动的):

$export_data = array (
  1,
  2,
  3,
  4,
  5,
  '',
  '',
  '',
  9,
  10,
);