I have a PHP multidimensional array that I need to selectively print to excel writer. I have something like this:
array(2) {
[10227]=>
array(9) {
["user"]=>
string(5) "10227"
["talk_time"]=>
string(1) "8"
["acw"]=>
string(1) "0"
["idle"]=>
string(1) "6"
}
[10236]=>
array(9) {
["user"]=>
string(5) "10236"
["talk_time"]=>
string(2) "10"
["acw"]=>
string(1) "3"
["idle"]=>
string(1) "0"
}
}
And in excel I need it to look kinda' like this:
User | talk_time | acw | idle
10227 | 8 | 0 | 6
10236 | 10 | 3 | 0
I think I can manage the 'writing' to excel, but I cannot seem to get the php to selectively write the value for each field where and how I want it. I've read a lot and have tried many things, I think the answer would be to use two foreach loops one for the 'initial' array and another one for the second dimension array, but for some reason I cannot make it work. I've also tried using 'extract' but it didn't go too well... I'm not a 'trained' PHP programmer. Google has been my university (and stackoverflow my faculty) and though I don't have too much trouble working with arrays..., the world goes upside down with multidimensional arrays...
Any help would be GREATLY appreciated.
Thanks!
-----EDIT----- Ok, I do not need the 'export to Excel' feature, I can handle that once I can assign the value of the array to a variable.
I'm currently doing this:
foreach ($agents as $row){
$USER=$row["user"];
echo "$USER\n";
foreach($row as $col){
$TALK_SEC=$col["talk_sec"];
}
}
But all I'm getting is
1023610236102361023610236102361023610236102361023610236102361023610236102361023610236102361023610236102361023610236
which is my first agent (I'm limiting my query to 1 -LIMIT 1-) times 24 times. If I add an echo to $TALK_SEC
, I would get the first number of each of the three four fields I'm querying about times the 24 times the agent will be 'spit' out....
FINAL EDIT AND ANSWER
I was able to get it to work using actually a single foreach statement:
foreach ($agents as $row){
//VAR_DUMP($row);
$USER=$row['user'];
$TALK=$row['talk_time'];
$ACW=$row['acw'];
$IDLE=$row['idle'];
Now all I have to do is print the variable names ($USER
, $TALK
, etc...) in the spreadsheet that I've already created with PEAR::EXCEL_WRITER
. Of course you need to create a loop to iterate over the different $USERS
that your query will output.
This script can generate file excel. But in your case you need format your array to put:
User | talk_time | acw | idle
10227 | 8 | 0 | 6
10236 | 10 | 3 | 0
The Script:
<?php
$file="demo.xls";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
$array = array(
array(10, 15, 20),
array(10, 15, 20),
array(10, 15, 20)
);
?>
<table>
<?php foreach($array as $row): ?>
<tr>
<?php foreach($row as $col):?>
<td><?php echo $col ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>