Echo foreach循环内部数组[关闭]

I have the following code and when I try to print the $test_array values in the array below with a space like this "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);

You are overwriting the entire $test_data on each loop iteration. Perhaps you mean to add to it via [] instead:

// 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')  
  );
}

Now each value of $row in your second loop should be an array containing two sub-arrays, the second having a different value for $x.

Note: there isn't actually a need to loop over $test_data in order to var_dump() each element's contents. Simply dump out the whole multidimensional array:

echo '<pre>'; 
var_dump($test_data);
echo '</pre>';

Outputs:

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"
    }
  }
}

Use implode:

echo implode(" ", $test);

You always overwrite the $test_data variable in your loop.

Uses $test_data[] = array();

$test= array('111','222');

foreach($test as $x)
{ 
    $test_data[] = array(  
        array('Invoice #', 'Name', 'Email'),  
        array( $x, 'Jhon', 'test@yahoo.com')  
    );
}

foreach( $test_data as $row )  
{  
    echo '<pre>'.var_dump($row);  
} 

You're re-writing $test_data each time the loop occurs. Try bringing it out of the loop and using [] instead:

$test= array('111','222');
$test_data = array();
foreach($test as $x){ 
    $test_data[] = array(
        'Invoice #' => $x,
        'Name' => 'Jhon',
        'Email' => 'test@yahoo.com'
    );
}
foreach($test_data as $row) {  
    echo "<pre>";
    print_r($row);
    echo "</pre>";
} 

You can also combine those two arrays into one (shown in the above example).