如何从数组中获取列名并导出到excel

时间:2014-04-04 06:16:36

标签: php mysql

Array
(
    [user_id] => 5
    [member_type] => 3
    [member_name] => Abin
    [email] => abin@newagesmb.com
    [username] => abin
    [about_user] => 
    [password] => e10adc3949ba59abbe56e057f20f883e
    [description] => 
    [membership_type] => 0
    [joindate] => 0000-00-00 00:00:00
    [membership_expirydate] => 0000-00-00 00:00:00
    [image] => 
    [active] => N
    [approved] => Y
    [varified] => N
    [coach] => N
    [paid_user] => N
    [fb_unique_id] => 
    [fb_access_tocken] => 
    [gender] => M
    [latitude] => 
    [longitude] => 
    [firstname] => 
    [lastname] => 
    [location] => 
    [avg_speed] => 6-8 Miles/Hour
    [twitter_tocken] => 
    [twitter_tocken_secret] => 
    [sponsor] => N
    [no_of_runs] => 0
    [rand] => 
    [distance] => 
    [country_id] => 
    [state_id] => 
)

这是我的阵列。我需要将这些值导出到excel。阵列可以是多维的。

4 个答案:

答案 0 :(得分:2)

在这里,如果您的数组键是您的列名,那么您可以使用array_keys

$columns = array_keys($your_array);

答案 1 :(得分:0)

更好地使用foreach循环

foreach($arr as $key=>$value)
{
   $contents[]=$key;
}

获得密钥后,您可以导出如下所示

<?php
$filename ="excelreport.xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.$filename);
print_r($contents);
 ?>

答案 2 :(得分:0)

$array = array(your data);

foreach($array as $col=>$value){

       $ff []= $col;
}


$data = $ff[1].",".$ff[2].",".$ff[3].","....so on

$excel = "xfile.csv";

file_put_content($excel, $data PHP_EOL, PHP_APPEND)

答案 3 :(得分:0)

使用PHPExcel库:

// Require the library
require_once '../libraries/PHPExcel/Classes/PHPExcel.php';

// Create new PHPExcel spreadsheet object
$objPHPExcel = new PHPExcel();

// Add your array of data to the PHPExcel spreadsheet object
$objPHPExcel->setActiveSheetIndex(0)
    ->fromArray(array_keys($myArrayOfData[0]), null, 'A1')
    ->fromArray($myArrayOfData, null, 'A2');

// Save the PHPExcel spreadsheet object to an OfficeOpenXML format Excel file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('mySparklyShineyExcelFile.xlsx');