select性地打印multidimensional array
我有一个PHPmultidimensional array,我需要有select地打印到Excel作家。 我有这样的东西:
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" } }
而在Excel中,我需要它看起来像这样:
User | talk_time | acw | idle 10227 | 8 | 0 | 6 10236 | 10 | 3 | 0
我想我可以pipe理“写作”,但我似乎无法让PHP有select地写在每个领域的价值在哪里以及如何我想要的。 我读了很多东西,并尝试了很多东西,我想答案是使用两个foreach循环,一个用于“初始”数组,另一个用于二维数组,但由于某种原因,我无法使其工作。 我也尝试使用“提取”,但它不太好……我不是一个“训练有素”的PHP程序员。 Google一直是我的大学(和我的教职员队伍),虽然我没有太多的麻烦与arrays工作…世界倒过来多维arrays…
任何帮助将不胜感激。
谢谢!
—–编辑—–好吧,我不需要“导出到Excel”function,我可以处理,一旦我可以将数组的值分配给一个variables。
我目前正在这样做:
foreach ($agents as $row){ $USER=$row["user"]; echo "$USER\n"; foreach($row as $col){ $TALK_SEC=$col["talk_sec"]; } }
但是我得到的是
1023610236102361023610236102361023610236102361023610236102361023610236102361023610236102361023610236102361023610236
这是我的第一个代理(我限制我的查询1 -LIMIT 1-)24倍。 如果我给$TALK_SEC
添加一个回$TALK_SEC
,我会得到我询问的24个代理将“吐”出来的三个四个字段中每一个的第一个数字….
最终编辑和答案
我能够使用实际上一个单一的foreach语句来工作:
foreach ($agents as $row){ //VAR_DUMP($row); $USER=$row['user']; $TALK=$row['talk_time']; $ACW=$row['acw']; $IDLE=$row['idle'];
现在我所要做的就是在电子表格中打印已经用PEAR::EXCEL_WRITER
创build的variables名称( $USER
, $TALK
等)。 当然,你需要创build一个循环遍历你的查询将输出的不同$USERS
。
这个脚本可以生成文件excel。 但在你的情况下,你需要格式化你的数组:
User | talk_time | acw | idle 10227 | 8 | 0 | 6 10236 | 10 | 3 | 0
剧本:
<?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>
这只是在这里已经发布的答案的补充…它只是显示了如何在Excel文件中包含数组的标题。 将其他人的post标记为已回答,而不是我的post,如果这是对你有用的。
输出:
user talk_time acw idle 10227 8 0 6 10236 10 3 0
码:
<?php $array = array ( 10227 => array ( 'user' => '10227', 'talk_time' => '8', 'acw' => '0', 'idle' => '6', ), 10236 => array ( 'user' => '10236', 'talk_time' => '10', 'acw' => '3', 'idle' => '0', ), ); $file="demo.xls"; header("Content-type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=$file"); $index = array_slice($array,0,1); $index = array_keys($index[0]); ?> <table> <tr> <?php foreach($index as $heading): ?> <th><?php echo $heading ?></th> <?php endforeach; ?> </tr> <?php foreach($array as $row): ?> <tr> <?php foreach($row as $col):?> <td><?php echo $col ?></td> <?php endforeach; ?> </tr> <?php endforeach; ?> </table>