簡體   English   中英

PHP將索引數組導出為CSV

[英]PHP Export Indexed Array into 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列中導出。

怎么可以這樣做呢?

如果我理解正確,你想在數據之間放置自由列,所以鍵匹配列號。

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

這里演示: 現場演示

要描述它,只需循環遍歷數組並檢查是否設置了密鑰,如果是,則將其值賦值給下一個數組,如果不是,則賦值為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);
}

老兄,你去吧。

$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 down或被指控為巫術。

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

我只是用空列的空值完全填充數組:

$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,
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM