我有以下代码,当我尝试$test_array使用类似"111 222"的空格打印下面数组中的值时:
$test_array= array('111', '222');
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Cache-Control: no-store, no-cache');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
$test_data = array(
array('Invoice #', 'Name', 'Email'),
array( $test_array, 'John', 'test@yahoo.com')
);
foreach( $test_data as $row )
{
fputcsv($output, $row, ',', '"');
}
fclose($output);
Run Code Online (Sandbox Code Playgroud)
您$test_data在每次循环迭代时覆盖整个.也许你的意思是通过以下方式添加到它[]:
// Initialize it before the first loop.
$test_data = array();
// Inside the inner loop...
foreach($test as $x){
// Append to the $test_data array with []
$test_data[] = array(
array('Invoice #', 'Name', 'Email'),
array( $x, 'Jhon', 'test@yahoo.com')
);
}
Run Code Online (Sandbox Code Playgroud)
现在$row,第二个循环中的每个值都应该是一个包含两个子数组的数组,第二个数组具有不同的值$x.
注意:实际上不需要$test_data为var_dump()每个元素的内容循环.只需转储整个多维数组:
echo '<pre>';
var_dump($test_data);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)
Array(2) {
[0]=>
array(2) {
[0]=>
array(3) {
[0]=>
string(9) "Invoice #"
[1]=>
string(4) "Name"
[2]=>
string(5) "Email"
}
[1]=>
array(3) {
[0]=>
string(3) "111"
[1]=>
string(4) "Jhon"
[2]=>
string(14) "test@yahoo.com"
}
}
[1]=>
array(2) {
[0]=>
array(3) {
[0]=>
string(9) "Invoice #"
[1]=>
string(4) "Name"
[2]=>
string(5) "Email"
}
[1]=>
array(3) {
[0]=>
string(3) "222"
[1]=>
string(4) "Jhon"
[2]=>
string(14) "test@yahoo.com"
}
}
}
Run Code Online (Sandbox Code Playgroud)