dongranding3909 2012-05-16 17:21
浏览 93

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);
  • 写回答

4条回答 默认 最新

  • douhu8851 2012-05-16 17:23
    关注

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

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器