First of all I use this class for creating excel files via XML: https://github.com/oliverschwarz/php-excel
My headers that I want to export to Excel;
$headers = array("A","B","C");
My arrays that I want to export to Excel;
$example = array("a1","a2","a3");
$example2 = array("b1","b2","b3");
$example3 = array("c1","c2","c3");
Then I merge my arrays in 1 array with these codes;
$result = array($headers,$example,$example2,$example3);
In conclusion I start the action;
$xls = new Excel_XML('UTF-8', false, 'Test');
$xls->addArray($result);
$xls->generateXML('xls-file');
After that, these class creates a XLS file as expected but; that XLS file scheme is unexpected because of my arrays's types. So I need help my friends, what should I do? Thanks...
Output is like that;
A_|__B__|_C
A1|__A2_|_A3
B1|__B2_|_B3
C1|__C2_|_C3
Output I desire is like that;
A_|__B__|_C
A1|__B1_|_C1
A2|__B2_|_C2
A3|__B3_|_C3
You can use array_map()
to re-organise the data from your results and then use array_unshift()
to push in the headers to the start of the array...
$result = array_map(null, $example, $example2, $example3);
array_unshift($result, $headers);
print_r($result);
which will give.
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
)
[1] => Array
(
[0] => a1
[1] => b1
[2] => c1
)
[2] => Array
(
[0] => a2
[1] => b2
[2] => c2
)
[3] => Array
(
[0] => a3
[1] => b3
[2] => c3
)
)
If your data is created as an array of arrays, then the following does the same sort of thing, passing the array in using ...
to pass each element in as a new parameter...
$example = [ ["a1","a2","a3"], ["b1","b2","b3"], ["c1","c2","c3"]];
$result = array_map(null, ...$example);
array_unshift($result, $headers);
print_r($result);
Each array is straightforwardly turned into a row in Excel. Therefore you need to create your array structure to match the rows you want in Excel:
$example = array("a1","b2","c1");
$example2 = array("a2","b2","c2");
$example3 = array("a3","b3","c3");
If in reality these arrays are generated from some other data source (rather than being hard-coded, as shown in your question) then you'll have to modify the code which generates them so that it creates the correct layout. Since you didn't share any code like that, I can't help directly with such a process.