我有下面的索引数组
$export_data = array (
[0] => 1,
[1] => 2,
[2] => 3,
[3] => 4,
[4] => 5,
[8] => 9,
[9] => 10,
);
我知道如何使用fputcsv将其导出到csv。然而,我的问题是,我需要将数据导出到正确的列,即$export_data8中的值需要在第9列中导出,而不是在第6列中导出。
请怎么做?
发布于 2016-10-13 14:31:17
给你,老大。
$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
现在来解释一下,这样我就不会被投反对票,也不会被指控巫术。
$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);
发布于 2016-10-13 14:12:53
如果我正确理解,您希望在数据之间放置空闲列,因此键与列号匹配。
$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);
}
发布于 2016-10-13 14:15:29
我只需将空列的空值完全填充数组:
$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,
);
https://stackoverflow.com/questions/40023259
复制相似问题