-5

次のコードがあり、$test_arrayこの「111222」のようなスペースを使用して以下の配列の値を出力しようとすると、次のようになります。

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

4 に答える 4

6

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

これで、2番目のループのの各値は$row2つのサブ配列を含む配列になり、2番目の値は。の値が異なります$x

注:実際には、各要素の内容$test_dataにループする必要はありません。var_dump()多次元配列全体を単純にダンプします。

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

出力:

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"
    }
  }
}
于 2012-05-16T17:23:36.997 に答える
0

ループ内の$test_data変数は常に上書きします。

$ 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);  
} 
于 2012-05-16T17:28:26.557 に答える
0

ループが発生するたびに$test_dataを書き直しています。ループから外して、代わりに[]を使用してみてください。

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

これらの2つのアレイを1つに結合することもできます(上記の例を参照)。

于 2012-05-16T17:29:07.403 に答える
0

内破を使用する:

echo implode(" ", $test);
于 2012-05-16T17:25:33.483 に答える